Answer to Question #24441 in C++ for satyam

Question #24441
main
{
int a[2] = {2,3};
printf("before swapping: %d %d\n",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("after swapping: %d %d\n",a[0],a[1]);
}
1
Expert's answer
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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS