为什么交换xor工作正常在c ++,但在java不?一些谜题 [英] Why swap with xor works fine in c++ but in java doesn't ? some puzzle
问题描述
示例代码
int a=3;
int b=4;
a^=(b^=(a^=b));
在c ++中它交换变量,但是在java中我们得到a = 0,b = 4为什么? / p>
In c++ it swaps variables, but in java we get a=0, b=4 why?
推荐答案
通过在一个语句中写你的swap all,你依赖内部的副作用 =
a ^ =(...)
表达式的表达式。你的Java和C ++编译器在做不同的事情。
By writing your swap all in one statement, you are relying on side effects of the inner a^=b
expression relative to the outer a^=(...)
expression. Your Java and C++ compilers are doing things differently.
为了正确地进行xor交换,你必须至少使用两个语句:
In order to do the xor swap properly, you have to use at least two statements:
a ^= b;
a ^= (b ^= a);
但是,交换变量的最好方法是使用临时变量让编译器选择最好的方法来实际做:
However, the best way to swap variables is to do it the mundane way with a temporary variable, and let the compiler choose the best way to actually do it:
int t = a;
a = b;
b = t;
在最好的情况下,编译器会根据 上面的交换,并且将简单地开始处理保存 a
和 b
的寄存器。你不能写任何棘手的xor代码,根本没有代码。
In the best case, the compiler will generate no code at all for the above swap, and will simply start treating the registers that hold a
and b
the other way around. You can't write any tricky xor code that beats no code at all.
这篇关于为什么交换xor工作正常在c ++,但在java不?一些谜题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!