Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!lll-winken!uunet!littlei!omepd!mipos3!pinkas From: pinkas@hobbit.intel.com (Israel Pinkas ~) Newsgroups: comp.unix.questions Subject: Re: Re^2: Bit Switching - How? Message-ID: Date: 11 Apr 89 21:05:11 GMT References: <1138@uvm-gen.UUCP> <9977@smoke.BRL.MIL> <2345@van-bc.UUCP> <2255@solo5.cs.vu.nl> <1574@lznv.ATT.COM> <1558@zen.UUCP> Sender: news@mipos3.intel.com Distribution: comp Organization: Corporate CAD, INTeL Corporation, Santa Clara, CA Lines: 64 In-reply-to: frank@zen.co.uk's message of 10 Apr 89 10:48:08 GMT In article <1558@zen.UUCP> frank@zen.co.uk (Frank Wales) writes: > In article <1574@lznv.ATT.COM> jlw@lznv.ATT.COM (J.L.WOOD) writes: > >> sl@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 #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@relay.cs.net CSNET: pinkas@cadev4.intel.com