views:

146

answers:

2

Possible Duplicate:
Why is this statement not working in java x ^= y ^= x ^= y;

Sample code

int a=3;
int b=4;
a^=(b^=(a^=b));

In c++ it swaps variables, but in java we get a=0, b=4 why?

+7  A: 

That's not guaranteed to work in C++ either. It's undefined behavior.

You should do it in three separate statements:

a ^= b; 
b ^= a;
a ^= b;
reko_t
The reason being that not-strictly speaking between two sequence points(e.g. a ;) a variable may not change more than once, lest undefined behavior
Armen Tsirunyan
+7  A: 

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.

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;

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.

Greg Hewgill
Note that "doing the XOR swap properly" doesn't work in the edge case that `a` and `b` are the same variable.
Graham Lee
+1 for a more ideomatic way to swap variables.
Gorgen
thanks a lot...
skydreamerr