swap two integer variables
Hi there,
while learning for my “Applied Computer Science” test with algorithms and data structures I found some funny thing :-)
Changing the content of two variables is mostly done by a temporary variable.
Stand back (in memory of xkcd’s regex comic) - this is not necessary anymore.
Wikipedia shows us this: http://en.wikipedia.org/wiki/XOR_swap_algorithm
So just do a:
x ^= y;
y ^= x;
x ^= y;
(Also worth reading: http://prabhagovind.wordpress.com/2007/02/09/3-ways-to-swap-variables-without-temp-variable).
But stop! This is not really obvisious but can be easily red. So for bonus points you can use the following oneliner:
y^=x^=y^=x
Have fun :-) Sven