[comp.lang.c] swap via xor

chris@mimsy.UUCP (Chris Torek) (01/28/88)

Let me see if I can lay this to rest.

	a ^= b; b ^= a; a ^= b;

will swap `a' and `b' if the `^' operator can be applied at all.
There is no way within C (short of `#define a b' or equivalent) to
make this fail.  On the other hand,

	*p ^= *q; *q ^= *p; *p ^= *q;

can fail if p==q.  This is what whoever-it-was meant when he said
that the first form could fail if a==b.  He did not mean `if the
values are equal', he meant `if the variables are identical'.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris

tainter@ihlpg.ATT.COM (Tainter) (01/30/88)

In article <10366@mimsy.UUCP>, chris@mimsy.UUCP (Chris Torek) writes:
> Let me see if I can lay this to rest.

If you hadn't said this I probably would have let it go. :-)

> 	a ^= b; b ^= a; a ^= b;
> will swap `a' and `b' if the `^' operator can be applied at all.
> There is no way within C (short of `#define a b' or equivalent) to
> make this fail.

Actually if a or be are expressions with side effects you have a problem.
i.e.

	given
	char *a, *b; 

	swap(a++,b++);

	defined as above goes splooot.

> In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)

--j.a.tainter

jay@splut.UUCP (Jay Maynard) (02/06/88)

In article <10366@mimsy.UUCP>, chris@mimsy.UUCP (Chris Torek) writes:
> [...]  This is what whoever-it-was meant when he said
> that the first form could fail if a==b.  He did not mean `if the
> values are equal', he meant `if the variables are identical'.

This is a very clear explanation of the difference. Being the semi-converted
Pascalite that I am (why, jsut yesterday, I did some more work on a W-2
reporting package I wrote in Turbo, but that's not important right now), the
distinction was kinda lost on me (I saw the point that swap(p,p) didn't
work, but couldn't for the life of me figure out why you'd want to swap
something with itself!)

-- 
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.