Thursday, June 14, 2007

Swapping

Write a one liner in C/C++ for swapping 2 integers.


Solution:

void swap(int &a, int &b) {
a^=(b^=(a^=b));
}

^ is the bitwise XOR operator. Yeah, it looks like magic... but it's actually not too tough to figure out once you get the gist of the idea. It's tricky, definitely.

No comments: