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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
By writing your swap all in one statement, you are relying on side effects of the inner
a^=bexpression relative to the outera^=(...)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:
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:
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
aandbthe other way around. You can’t write any tricky xor code that beats no code at all.