Is this swap() macro correct?

bdm659 at csc.anu.oz bdm659 at csc.anu.oz
Mon Jan 22 23:34:13 AEST 1990


In article <17709 at rpp386.cactus.org>, woody at rpp386.cactus.org (Woodrow Baker) writes:
> In article <113.25B72444 at tqc.FIDONET.ORG>, eric at 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 at anucsd.oz.au  or  bdm659 at csc1.anu.oz.au



More information about the Comp.lang.c mailing list