Re^2: Bit Switching - How?

Israel Pinkas ~ pinkas at hobbit.intel.com
Wed Apr 12 07:05:11 AEST 1989


In article <1558 at zen.UUCP> frank at zen.co.uk (Frank Wales) writes:

> 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...
>
> Well, this surprised me, since blurfl^blurfl does give 0, but blurfl^0
> gives blurfl again, so you should get it back, unless some pretty funky
> pointer-to-int conversion is taking place.  I tried the following
> myself (admittedly on a fairly well-behaved machine from HP),

[Code 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.]  Or is there some portability problem
> lurking here that my Monday morning mind has missed?

This fails if you pass the same object to swap() for both arguments.  The
code that Frank posted passed two copies of the object:

#include <stdio.h>

#define	swap(a,b) {a^=b;b^=a;a^= b;}

main()

{
    int a = 10, b = 10, c = 10;

    printf("a = %x   b = %x   c = %x\n", a, b, c);
    swap(a,a)
    swap(b,c)
    printf("a = %x   b = %x   c = %x\n", a, b, c);
}

Results in:

a = a   b = a   c = a
a = 0   b = a   c = a


A compiler that gives different results is probably broken.

-Israel Pinkas
--
--------------------------------------
Disclaimer: The above are my personal opinions, and in no way represent
the opinions of Intel Corporation.  In no way should the above be taken
to be a statement of Intel.

UUCP:	{amdcad,decwrl,hplabs,oliveb,pur-ee,qantel}!intelca!mipos3!cadev4!pinkas
ARPA:	pinkas%cadev4.intel.com at relay.cs.net
CSNET:	pinkas at cadev4.intel.com



More information about the Comp.unix.questions mailing list