Path: utzoo!attcan!uunet!zaphod.mps.ohio-state.edu!julius.cs.uiuc.edu!ux1.cso.uiuc.edu!heal From: heal@ux1.cso.uiuc.edu (Loren Heal) Newsgroups: comp.lang.c Subject: Efficient swap() Summary: Terse way to #define swap() Keywords: tricky macro from hell Message-ID: <1991Jan13.050236.11634@ux1.cso.uiuc.edu> Date: 13 Jan 91 05:02:36 GMT Organization: University of Illinois at Urbana Lines: 23 ----------------- 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@ux1.cso.uiuc.edu, *net!uiucuxc!ux1!heal. -- *----------------------------------------------------------------------* : Loren E. Heal : leheal@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!) :