C awesomeness
This is some awesome C code. See if you can figure out what it does, and send me an email or something if it makes you happy when you figure it out. It sure made me happy!<p/>
// assume x and y are two variables of the same type x ^= y; y ^= x; x ^= y;
Anyway, I posed this as a puzzle before. Hopefully you had time to think about it. Here’s the solution:<p/>
This swaps the contents of the variables, without using a temporary swap space! It’s so wonderful. Apparently this is a reasonably well-known algorithm, and nobody told me about it before. Oh well. Hopefully someone was enlightened by it.<p/>
If you don’t understand how it works, I’ll explain. You should know that ^ is the XOR operation, and x ^= y means “XOR x and y, and store the result into x.” After the first statement, y is unchanged, and the new x contains the xor of the old x and y. Now on to the second statement – y ^= x
. When you do that, you are going to xor y with the new x. This gets you the old x, and stores it into y! (A very useful property of XOR is that (x^y)^x = y
, and (x^y)^y = x
.) Now the last statement takes new-x (the xor), xors it with old-x to produce y, and stores it back in x. So the result is that x contains oldy, and y contains oldx.<p/>