Monday, February 23, 2009

Temporariless Swap

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;
}

Author : Guille

0 nhận xét:

Post a Comment