Can someone explain to me how XOR swapping of two variables with no temp variable works?
void xorSwap (int *x, int *y) { if (x != y) { *x ^= *y; *y ^= *x; *x ^= *y; } }
I understand WHAT it does, but can someone walk me through the logic of how it works?
You can see how it works by doing the substitution:
Substituting,
Because xor is fully associative and commutative:
Since
x xor x == 0for any x,And since
x xor 0 == xfor any x,And the swap is done.