[comp.lang.c] swap macro -- beware -- oh yeah ?

dag@chinet.UUCP (Daniel A. Glasser) (01/29/88)

In article <3061@killer.UUCP> jfh@killer.UUCP (John Haugh) writes:
[a ^= b; b ^= a; a ^= b;]
>What if, A and B are aliases?
What do you mean by aliases?  Are they both the same storage or just
the same value?
>
>	let's say, A = B = 7.
okay, they are similar values but different storage.
>	after a ^= b, both a and b == 0.
Nope, a == 0, b still == 7
>	then, after both b ^= a and a ^= b (the second time), a and b
>	are STILL == 0.
No again, after b ^= a, a == 0 and b ==7, and now after a ^= b,
a == 7 and b == 7.  I think you are being too quick to attack.

This dosn't hold up, of course if &a == &b, but depending on how
your compiler handles constant expressions, and assuming you don't
use pointers, a macro like the following:
#define swap(a,b)	if(&(a)!=&(b)){(a)^=(b);(b)^=(a);(a)^=b}
might evaluate to the same code as without the "if", since &a and
&b will usually be constant expressions (even if they are autos or
paramters, there relative addresses will be known).  As I said,
it depends on your compiler.

-- 
Nobody at the place where I work	Daniel A. Glasser
knows anything about my opinions	...!ihnp4!chinet!dag
my postings, or me for that matter!	...!ihnp4!mwc!dag
					...!ihnp4!mwc!gorgon!dag
	One of those things that goes "BUMP!!! (ouch!)" in the night.

jfh@killer.UUCP (The Beach Bum) (01/29/88)

In article <1182@ark.cs.vu.nl>, maart@cs.vu.nl (Maarten Litmaath) writes:
> In article <3061@killer.UUCP> jfh@killer.UUCP (John Haugh) writes:
> \	a ^= b;
> \	b ^= a;
> \	a ^= b;	[ I think this was the code in that article ]
> \
> \What if, A and B are aliases?
> \
> \	let's say, A = B = 7.
> \	after a ^= b, both a and b == 0.
> \	then, after both b ^= a and a ^= b (the second time), a and b
> \	are STILL == 0.
> 
> I think this is not true, you're making a mistake.
> -- 
> Time flies like an arrow, fruit flies |Maarten Litmaath @ Free U Amsterdam:
> like an orange.      (seen elsewhere) |maart@cs.vu.nl, mcvax!botter!ark!maart

I may have missed something in the definition of what an alias is, but in
my book (okay Chris, I won't name names ;-), an alias is a different name
for the same something.  Different name, same storage, person, place,
fruit fly, whatever.

XOR - truth table.

	A	B	O+ (no overprinting here)
	0	0	0
	0	1	1
	1	0	1
	1	1	0

So far so good Maarten?  What if, A and B are aliases?  Well, wipe out
the lines for A != B and what is left in the O+ column? 0.  Now do this for
all those bits.  All 32 or whatever of them.  You get 0.  Lots of times.

- John.
-- 
John F. Haugh II                  SNAIL:  HECI Exploration Co. Inc.
UUCP: ...!ihnp4!killer!jfh                11910 Greenville Ave, Suite 600
"Don't Have an Oil Well? ...              Dallas, TX. 75243
 ... Then Buy One!"                       (214) 231-0993 Ext 260