Path: utzoo!mnetor!uunet!nuchat!splut!jay From: jay@splut.UUCP (Jay Maynard) Newsgroups: comp.lang.c Subject: Re: comma operator Message-ID: <352@splut.UUCP> Date: 31 Jan 88 16:29:03 GMT References: <3819@sigi.Colorado.EDU> <5080013@hpfcdc.HP.COM> <7120@brl-smoke.ARPA> <564@cresswell.quintus.UUCP> Organization: Confederate Microsystems, League City, TX Lines: 34 Summary: Uhm...are you sure about the XOR swap setting two equal operands to 0? In article <564@cresswell.quintus.UUCP>, ok@quintus.UUCP (Richard A. O'Keefe) writes: > > In article <2382@ihuxv.ATT.COM> rck@ihuxv.ATT.COM (R. C. Kukuk) writes: > > >> In article <3887@sigi.Colorado.EDU> swarbric@tramp.Colorado.EDU (SWARBRICK FRANCIS JOHN) writes: > > >> >#define swap(a,b) ((a) = ((b) = ((a) = (a) ^ (b)) ^ (b)) ^ (a)) > > >This oldie fails when a == b. Why? Think about it. > swap(a, a); > sets a to 0, whatever its previous value was. If you do > swap(*p, *q); > it can easily happen that p==q, in which case you get this problem. Let's explode the macro, and see what it does: p = 5; q = 5; swap(p,q); the swap macro becomes: ((p) = ((q) = ((p) = (p) ^ (q)) ^ (q)) ^ (p)) stripping redundant parentheses: p = (q = (p = p ^ q) ^ q) ^ p substituting variables, from the inside out: p = (q = (p = 5 ^ 5) ^ q) ^ p (assigns 0 to p, temporarily) p = (q = 0 ^ 5) ^ p (assigns 5 to q) p = 5 ^ 0 (assigns 5 to p) This case still works. As pointed out before, though, this macro has other problems. -- Jay Maynard, K5ZC (@WB5BBW)...>splut!< | GEnie: JAYMAYNARD CI$: 71036,1603 uucp: {uunet!nuchat,academ!uhnix1,{ihnp4,bellcore,killer}!tness1}!splut!jay Never ascribe to malice that which can adequately be explained by stupidity. The opinions herein are shared by none of my cats, much less anyone else.