Efficient swap()

Christopher R Volpe volpe at camelback.crd.ge.com
Tue Jan 15 02:56:01 AEST 1991


In article <1991Jan13.050236.11634 at ux1.cso.uiuc.edu>,
heal at ux1.cso.uiuc.edu (Loren Heal) writes:
|>
|>-----------------
|>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)

This is not legal C. (I mean using this macro is not legal. The
definition itself is fine.) It assumes that the assignments to the
variables occur during (or somehow in sync with) the evaluation of
each "^=" operator. They don't. The assignments occur sometime between
the previous and next sequence points (3.3.16). There are two assignments
to variable "A" in that expression. It's certainly possible that the
assignment corresponding to the rightmost assignment operator can
take place AFTER the assignment corresponding to the leftmost operator,
giving you garbage results. 

Section F.2 identifies the following as an example of a circumstance in
which the behavior is undefined: "An object is modified more than once, or
is modified and accessed other than to determine the new value, between
sequence points."

|>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!)                      :
                       
==================
Chris Volpe
G.E. Corporate R&D
volpecr at crd.ge.com



More information about the Comp.lang.c mailing list