Freigeben über


Coffee Break: Swapping Two Values Without Involving a Third One

Everybody knows the XOR bitwise operator. It returns 1 for every couple of bits that don’t match, 0 otherwise.

What not everybody may be aware is a curious feature of it: it may serve to swap integer values (char, short, int, long long or their unsigned versions).

Let’s see:

    // shemp contains 01000001 and curly 01011010 respectively
   char shemp = 'A', curly = 'Z';
   
   shemp ^= curly;      // shemp ends with 00011011
   
   curly ^= shemp;      // curly ends with 01000001
                        // that's shemp initial value
   shemp ^= curly;      // shemp ends with 01011010
                        // curly initial value

The snippet above show in slow-motion how two variables of the same kind end up by exchanging their values without needing a temporary one to hold the initial value of any of them so it won’t be lost when that variable is assigned the value of the other one. As long as variables to exchange are integers of a same kind, sign, it works. Floating-point variables (float, double, etc.) don’t lose your time casting as same-length-in-bytes integers, cheating the compiler or whatever: I’ve already tried and didn’t work.

There’s a mathematical explanation about why this XOR chain works as swapping algorithms although I haven’t read it (this is just a coffee break, not an algebra lecture). But if you are eager than me, here it goes: https://en.wikipedia.org/wiki/XOR_swap_algorithm#Proof_that_the_XOR_swap_works

Now let me challenge you for a bit: how can you swap two numbers of a same kind –not necessarily integer types this time- if you were allowed to use other basic operators and just three assignments? I’ll show the solution in the next coffee break.