Which of the following options can achieve a swapping effect for pair
(*, *)? Note that ^ represents XOR operation. For binary numbers, 0 XOR 0 = 0, 0 XOR 1 = 1, 1 XOR 0 = 1, 1 XOR 1 = 0.A.
(x, y): x ^= y ^= x ^= y;B.
(a[x], a[y]): a[x] ^= a[y] ^= a[x] ^= a[y];C.
(x, y): x -= y += x -= y;D.
(a[x], a[y]): a[x] -= a[y] += a[x] -= a[y];
I've seen that C and D are not logically correct. And A is correct I guess. But I'm not sure what's the difference between A and B?
Don't forget that the equal operations are interpreted from right to left.
Case A:
If x and y are integer variables of same type, the code is valid and swaps x and y
Case B:
It is pretty much the same as A,
xandyare not modified and are indices in an array. Ifa[]elements are integers, it is valid and swaps 2 items of the arrayaonly ifxandyare different!If
xandyare identical, ina[x] ^= a[y],a[x]anda[y]are the same l-value, and it is erased losing its initial value.Case C:
Case D:
Same as case C, but applies to elements of
a[]and also has issue ifxandyare identical.Note:
The equal operator is totally sequenced since C11. The standard stipulates for assignment (6.5.16)