98 952
Assignments Done
98.8%
Successfully Done
In May 2021

# Answer to Question #24441 in C++ for satyam

Question #24441
main
{
int a[2] = {2,3};
printf(&quot;before swapping: %d %d\n&quot;,a[0],a[1]);
//a[0] ^= a[1];
//a[1] ^= a[0];
//a[0] ^= a[1]; //this is working correctly.

a[0] ^= a[1] ^= a[0] ^= a[1]; //this didn't work correctly why?

printf(&quot;after swapping: %d %d\n&quot;,a[0],a[1]);
}
1
2013-02-18T08:44:01-0500
When using compound assignment operators, e.g
x += y;
which is equal to
x = x + y;
the lvalue (x) is evaluated only once.
It means that x is saved before calculating the sum x + y.

So in our case the left most a[0] value is evaluated before the right part is.
a[0] = 2, a[1] = 3
and
a[0] ^= (a[1] ^= a[0] ^= a[1]);
is equal to
a[0] = a[0] ^ (a[1] ^= a[0] ^= a[1]);
and it's equal to
a[0] = 2 ^ (a[1] ^= a[0] ^= a[1]);
Therefore after executing the part in brackets
(a[1] ^= a[0] ^= a[1])
a[1] will be equal to a[0] (2)
and a[0] ^ a[0] (or 2 ^ 2) gives us a zero.

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!