I came across an article on macros, and i noticed whoever wrote it used
this
#define SWAP(x,y) x ^= y; y ^= x; x ^= y;
to swap two values. I couldn't understand why it worked, and i still don't know.
So i did some calculations, and either whoever wrote that article is wrong, or
i messed up somewhere trying to solve this.
isn't it like a += only it's Xor instead of addition?
Yes... but do you understand what xor does? Because your example is wrong.
1 2 3 4
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
XOR has the property of neutralizing itself. That is a ^ a will be zero, no matter what a is.
This works as follows:
1 2 3 4 5 6 7 8
int X = x; // capital X is the ORIGINAL x
int Y = y; // capital Y is the ORIGINAL y
x ^= y; // at this point: x = X^Y and y = Y
y ^= x; // at this point: x = X^Y and y = Y ^ X ^ Y .... the Ys cancel out, so y = X
x ^= y; // at this point: x = X^Y^X ... the Xs cancel out, so X=y and y=X
// so the swap is complete
If you plug in numbers, it works the same:
1 2 3 4 5 6
x = 10; // 1010
y = 5; // 0101
x ^= y; // 1010 ^ 0101 = 1111... so x = 15 (%1111)
y ^= x; // 0101 ^ 1111 = 1010... so y = 10
x ^= y; // 1111 ^ 1010 = 0101... so x = 5
Just to add: you should never do this, as it is obscure and confusing at best, only works on integer types, and can also confuse the optimizer so you get slower swaps.