Temporariless Swap

This tip submitted by Guille on 2005-11-25 13:51:38. It has been viewed 64201 times.
Rating of 6.0 with 642 votes

Here's a neat trick to swap two variables without creating a temporary:

void swap(int& a, int& b)
{
a ^= b;
b ^= a;
a ^= b;
}

To check correctness, you only need to know that (a^b)^a = b and (b^a)^b = a.
Caveat: this will not work if \"a\" and \"b\" point to the same variable!.
In that case both will be reset to 0 after executing swap(a,b).
The correct version should look like this: