This tip submitted by Guille on 2005-11-25 13:51:38. It has been viewed 31143 times.
Rating of 3.8070 with 228 votes
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;
}
More tips
Add a tip!
-----
Interested in advertising
with us?
Please read our privacy
policy.
Copyright
© 1997-2005 Cprogramming.com. All rights reserved.