Friday, July 28, 2006

Stupid C++ tricks (repost)

Originally posted much earlier this year.


#define SWP(x,y) (y^=(x^=(y^=x)))

This may look like line noise, but is as close as I can come to a minimal-size implementation of "swap two values without using temporary storage". This was suggested by a challenge in Steve Oualline's Practical C++ Programming, to which I already knew the answer because I'd been asked it a couple years back, right after I'd done a crypto class and knew that the answer to anything difficult-sounding is always XOR. So I decided to try and condense it into a preprocessor function, yielding the above on the second try. Technically, I could make it shorter by taking out all but the outer parentheses, but I come from LISP and they are somewhat reassuring, in addition to ensuring correct function.

Go ahead, try it. The really neat thing about making it a preprocessor define is that this will now work on any arbitrary variables, as long as they're of the same bit width. It'll still work otherwise, it just won't produce correct results because the longer value will get truncated when it's XORed into the shorter one.

Thus, this is a proper preprocessor define: terse almost to the point of unreadiblity, useful in that it breaks rules established elsewhere (in this case any type checking that may apply), and potentially dangerous. This is also an excellent example of what CS nerds do when bored and unable to read their forums of choice.

No comments: