I don’t know who originated this trick.  I first read about in in P.J. Plauger’s “Programming on Purpose”.  It was probably first used by assembly language programmer’s when 4-bit systems were common and memory was paltry.  Still, it can be handy in a tight loop even on a relative fast processor.

The goal of the trick is to exchange the value of two elements without using a third memory location.  This is really quick when the values are stored in register variables. The C syntax looks like this:

a ^= b ^= a ^= b;

For those of you who are unfamiliar with C, ‘^’ is an XOR operation, and  ‘a ^= b’ is equivalent to ‘a = a ^ b’.  C allows expressions to cascade like this into a single statement, and compilers may in some cases, perform better optimizations on a statement like this than if it were broken into multiple statements.  On the other hand, if these were, in fact, register variables then in most cases the code above would be identical to:


a = a ^ b;
b = b ^ a;
a = a ^ b;
b = b ^ a;

I’ve always like this trick, and probably use it a bit too often.

About Max H:
Max is a father, a husband, and a man of many interests. He is also a consulting software architect with over 3 decades experience in the design and implementation of complex software. View his Linked-In profile at http://www.linkedin.com/pro/swarchitect