int x=1;
int y=2;
x ^= y ^= x ^= y;
I am expecting the values to be swapped.But it gives x=0 and y=1.
when i tried in C language it gives the correct result.
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.
Your statement is roughly equivalent to this expanded form:
Unlike in C, in Java the left operand of a binary operator is guaranteed to be evaluated before the right operand. Evaluation occurs as follows:
You could reverse the order of the arguments to each xor expression so that the assignment is done before the variable is evaluated again:
This is a more compact version that also works:
But this is a truly horrible way to swap two variables. It’s a much better idea to use a temporary variable.