Tuesday 17 January 2012

Why swap with xor works fine in c++ but in java doesn't ?

Look at the following java snippet:
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 / CPP language it gives the correct result.

So what is the reason...lets look at it:
x = x ^ (y = y ^ (x = x ^ y));

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:
x = x ^ (y = y ^ (x = x ^ y))
x = 1 ^ (y = 2 ^ (x = 1 ^ 2))
x = 1 ^ (y = 2 ^ (x = 3))
x = 1 ^ (y = 2 ^ 3)             // x is set to 3 
x = 1 ^ (y = 1)
x = 1 ^ 1                       // y is set to 1
x = 0                           // x is set to 0

You could reverse the order of the arguments to each xor expression so that the assignment is done before the variable is evaluated again:
x = (y = (x = x ^ y) ^ y) ^ x
x = (y = (x = 1 ^ 2) ^ y) ^ x
x = (y = (x = 3) ^ y) ^ x 
x = (y = 3 ^ y) ^ x             // x is set to 3
x = (y = 3 ^ 2) ^ x
x = (y = 1) ^ x
x = 1 ^ x                       // y is set to 1
x = 1 ^ 3
x = 2                           // x is set to 2
This is a more compact version that also works:
x = (y ^= x ^= y) ^ x;

But this is a truly horrible way to swap two variables. It's a much better idea to use a temporary variable.
int t = a;
a = b;
b = t;

Also, the xor logic will work, if we have 3 separate statement
a ^= b; 
b ^= a;
a ^= b;


No comments:

Post a Comment