Monday, May 22, 2006

Fancy code for swapping integers

Good evening.

While surfing the internet, I just came across some articles about bitwise operations in C. There I found a fancy code snippet for swapping two 'ints'. Well I never thought about it but if I had to code a little swapping procedure, it would probably something like this:

void swap(int* x, int* y)
{
int z = *x;
*x = *y;
*y = z;
}


Ok, quite easy. Just use a temporary variable... but there is another approach without a third variable, just look at this:

x ^= y;
y ^= x;
x ^= y;

Really cool xor-action, isn't it? Try to figure out what's going on here. (Tip: x ^ x = 0)
Well, every day I learn something new... but that's enough for now.
Good night. :-)

No comments: