Interesting way of swapping variables
March 12th, 2008
I found an interesting way of swapping two variables.
Normally I’d just use one of these functions:
void swap(int* i, int* j) { int t=*i; *i=*j; *j=t; }
or the xor (bitwise) way:
void xorSwap(int* i, int* j) { *i ^= *j; *j ^= *i; *i ^= *j; }
Instead of this you also could swap this kinda tricky way:
void swap_vars(int* i, int* j) { *j=*i+*j-(*i=*j); }
For the solution no temporary varbiables are getting used.
It also can be used for any data types and this is more efficient than the normal methods. Additionally it would be thinkable to implement it as a template function.
This little one liner is cute and all, but it is unreadable. So if you use it, you need to add a couple lines of comments saying what it does (not just “swap integers” as that will be assumed to be an out of date comment) which makes the effort of programming greater than using a temp variable.





