Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!wuarchive!julius.cs.uiuc.edu!rpi!crdgw1!camelback!volpe From: volpe@camelback.crd.ge.com (Christopher R Volpe) Newsgroups: comp.lang.c Subject: Re: Efficient swap() Keywords: tricky macro from hell Message-ID: <15660@crdgw1.crd.ge.com> Date: 14 Jan 91 15:56:01 GMT References: <1991Jan13.050236.11634@ux1.cso.uiuc.edu> Sender: news@crdgw1.crd.ge.com Reply-To: volpe@camelback.crd.ge.com (Christopher R Volpe) Lines: 35 In article <1991Jan13.050236.11634@ux1.cso.uiuc.edu>, heal@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@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!) : ================== Chris Volpe G.E. Corporate R&D volpecr@crd.ge.com