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]);

}

{

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]);

}

Expert's answer

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.

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.

## Comments

## Leave a comment