Temporariless Swap

This tip submitted by Guille on 2005-11-25 13:51:38. It has been viewed 69129 times.
Rating of 5.7 with 731 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:

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




More tips

Help your fellow programmers! Add a tip!