Obfuscated SWAP

DAVID NEWALL ccdn at levels.sait.edu.au
Fri Aug 25 20:55:06 AEST 1989


In article <784 at skye.ed.ac.uk>, ken at aiai.ed.ac.uk (Ken Johnson) writes:
> Well, I tried it and it works
>
>       x ^= y ^= x ^= y;       /* Swap X and Y over */
>
> I don't understand how it works


The intent of this code is clear.  It is intended to work like this:

Given the variables x and y, which have initial values a and b respectively.
Then:

       x ^= y ^= x ^= y
       |    |    |    |
       |    |    |    x = a, y = b
       |    |    |
       |    |    x = a ^ b, y = b
       |    |
       |    y = b ^ (a ^ b) = (b ^ b) ^ a = a, x = a ^ b
       |    => y = a, x = a ^ b
       |
       x = (a ^ b) ^ a = (a ^ a) ^ b = b, y = a
       => x = b, y = a

(You realise, of course, that ^ is the exclusive or operator)


David Newall                     Phone:  +61 8 343 3160
Unix Systems Programmer          Fax:    +61 8 349 6939
Academic Computing Service       E-mail: ccdn at levels.sait.oz.au
SA Institute of Technology       Post:   The Levels, South Australia, 5095



More information about the Comp.lang.c mailing list