Re^2: Bit Switching - How?
Frank Wales
frank at zen.co.uk
Tue Apr 11 19:10:16 AEST 1989
In article <1558 at zen.UUCP> I wrote:
>In article <1574 at lznv.ATT.COM> jlw at lznv.ATT.COM (J.L.WOOD) writes:
>>> sl at van-bc.UUCP (pri=-10 Stuart Lynne) writes:
>>> \For fast generic swapping I use:
>>>
>>> \#define swap(a,b) {a^=b;b^=a;a^= b;}
>>>
>>
>>Also be careful how you use this algorithm if you are using pointers.
>>I once used this method in a sorting routine as my basic exchange and
>>got badly burned.
>>
>>If a and b point to the same location, you get zero as in 0, nada, goose egg.
>
>Well, this surprised me,
[example of why I thought there was no problem deleted]
>I'd be interested to find out the machine on which this XOR trick
>fails to swap integral values correctly. [I hardly ever use it, but
>I'd still expect it to work.]
And indeed it does, except when a and b are the *same* (not the same
value, but the same object), because the first a^=b toasts both a and b,
and you've lost your recovery information.
>Or is there some portability problem
>lurking here that my Monday morning mind has missed?
Well, it's Tuesday now -- thanks to those who mailed me with a wake-up
call [I did say I hardly used the trick myself; good job, too ;-)].
--
Frank Wales, Systems Manager, [frank at zen.co.uk<->mcvax!zen.co.uk!frank]
Zengrange Ltd., Greenfield Rd., Leeds, ENGLAND, LS9 8DB. (+44) 532 489048 x217
More information about the Comp.unix.questions
mailing list