Re:Low Level Bit Hacks You Absolutely Must Know
by jibiki on Tuesday June 30, 2009 @06:51PM
(#681758)
He meant if they are the same variable, not the same value. (E.g., you pass pointers to your function.)
int swap(int * a, int * b)
{
(*a)^=(*b);
(*b)^=(*a);
(*a)^=(*b);
}
int x = 15;
int *y = &x;
int *z = &x;
swap(y,z); //Now *y == 0
Here's the general proof:
a ^= b (a = a ^ b, b = b)
b ^= a (a = a ^ b, b = b ^ (a ^ b) = a)
a ^= b (a = b ^ (a ^ b) = b ,b = a)
Now, let's replace all references initial values with constant c:
a ^= b (a = c ^ c = 0, b = c)
b ^= a (a = 0, b = c ^ 0 = c)
a ^= b (a = c ^ 0 = c, b = c)
Notice that at the end, you still end up with a = b = c. There are plenty of reasons not to use this approach, but that ain't one of them.