Efficient swap()

Loren Heal heal at ux1.cso.uiuc.edu
Sun Jan 13 16:02:36 AEST 1991


-----------------
Here is a one-line C macro, swap():  The principle is well-known, 
but I've never seen it done this tersely:

#define swap(A,B) (A^=B^=A^=B)

I admit that's not too readable.  It works for integer-compatible 
types, on the principles of the exclusive-OR operation.  Working 
from right to left, First A is xor'd with B, so that A is now A^B, 
B is still B.  Then B is xor'd with the A^B, which leaves the 
original value of A in B.  Then finally A (which is A^B) is xor'd 
with the original value of A, so that A contains the original 
value of B.  I usually use the alternative form

#define sort2(A,B) ((A>=B)?0:((A^=(B^=(A^=B))),1))

Loren Heal, heal at ux1.cso.uiuc.edu, *net!uiucuxc!ux1!heal.
-- 
*----------------------------------------------------------------------*
: Loren E. Heal : leheal at uiuc.edu (from *net, you figure it out)       :
:(Not a spokesman for the University of Illinois at Urbana-Champaign)  :
:(I may work there, but I still own my own mind!)                      :



More information about the Comp.lang.c mailing list