Is this swap() macro correct?

Woodrow Baker woody at rpp386.cactus.org
Sun Jan 21 15:39:31 AEST 1990


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
(that is you know where you came from), so you can xor where you came from
with the current node link and find out where you are going.  It saves a
pointer.  Adding a node entry, you know where you are going to insert it,
thus you know where you came from (the node just prior) and where  the next
node will reside, so you can use XOR to construct the pointer.

Just a sidelight...
Cheers
Woody
f
> Eric Rouse -- via The Q Continuum (FidoNet Node 1:382/31)
> UUCP: ...!rpp386!tqc!eric
> ARPA: eric at tqc.FIDONET.ORG



More information about the Comp.lang.c mailing list