Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!usc!elroy.jpl.nasa.gov!ames!uhccux!munnari.oz.au!csc!bdm659 From: bdm659@csc.anu.oz Newsgroups: comp.lang.c Subject: Re: Is this swap() macro correct? Message-ID: <1344.25bafdc5@csc.anu.oz> Date: 22 Jan 90 12:34:13 GMT References: <113.25B72444@tqc.FIDONET.ORG> <17709@rpp386.cactus.org> Organization: Computer Services, Australian National University Lines: 21 In article <17709@rpp386.cactus.org>, woody@rpp386.cactus.org (Woodrow Baker) writes: > In article <113.25B72444@tqc.FIDONET.ORG>, eric@tqc.FIDONET.ORG (Eric Rouse) writes: >> >> #define Swap(X1,X2) { X1 ^= X2; X2 ^= X1; X1 ^= X2; } >> >> It's quite nice for integers, unsigned, longs, pointers etc. Plus it >> doesn't use any temp storage. > I use xor for maintaing pointers for linked lists. As the above line of > code clearly shows, you can given a ^ b extract a or b if you know the > other one. If you are traversing a linked list, you know either a or b > ... The portability of this practice is not guaranteed by the ANSI C Standard. The arguments of ^ must have integral type, which doesn't include pointer types. You could try explicit casts, but there's no guarantee that any integral type is long enough to hold all the values of a pointer type and, even if there was, there is no guarantee that converting a pointer to an integral type and back to a pointer recovers the original value. The same goes for the Swap() macro above if X1 and X2 have pointer type. Brendan McKay. bdm@anucsd.oz.au or bdm659@csc1.anu.oz.au