comma operator

Jay Maynard jay at splut.UUCP
Mon Feb 1 02:29:03 AEST 1988


In article <564 at cresswell.quintus.UUCP>, ok at quintus.UUCP (Richard A. O'Keefe) writes:
> > In article <2382 at ihuxv.ATT.COM> rck at ihuxv.ATT.COM (R. C. Kukuk) writes:
> > >> In article <3887 at sigi.Colorado.EDU> swarbric at 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.



More information about the Comp.lang.c mailing list