[net.lang.c] using ^= to swap two integers

arnold@gatech.UUCP (Arnold Robbins) (02/09/85)

I blew it:

>>  Jon Shapiro
>   me

>> 	To exchange two items without an intermediate variable, try:
>> 
>> 	b ^= a ^= b ^= a
>> 
>> Jon Shapiro
>
>However, if a == b when you start out, you end up with a == 0 && b == 0.

I tried it, and in fact it does end up swapping them, but since they were
equal in the first place, it is a null op.  Several people have pointed out
to me that I was wrong, so please, no more mail.  I goofed.

(Here is the program which proved me wrong.)
main()
{
	int a = 3, b = 3;

	b ^= a ^= b ^= a;

	printf ("a = %d\tb = %d\n", a, b);
}
-- 
Arnold Robbins
CSNET:	arnold@gatech	ARPA:	arnold%gatech.csnet@csnet-relay.arpa
UUCP:	{ akgua, allegra, hplabs, ihnp4, seismo, ut-sally }!gatech!arnold

Help advance the state of Computer Science: Nuke a PR1ME today!

roy@phri.UUCP (Roy Smith) (02/11/85)

>To exchange two items without an intermediate variable, try:
> 	b ^= a ^= b ^= a
> [and so on and so on]

Who cares?  The xor trick may be cute, but if any programmer that works
for me tries to put that kind of crap in his code to make it run faster,
s/he should probably start looking for another job.  Can we move this to
net.lang.c.worthless.trivia?
-- 

The opinions expressed herein do not necessarily reflect
the views of the Public Health Research Institute.

allegra!vax135!timeinc\
   cmcl2!rocky2!cubsvax>!phri!roy (Roy Smith)
         ihnp4!timeinc/

jlw@ariel.UUCP (J.WOOD) (02/12/85)

Regarding swapping via the xor operation as in:


	b ^= a ^= b ^= a;
	
be careful that a and b are not at the same address
as when using pointers.  In that case the value(s) are (both)
set to zero.  I got burned on this once.



					Joseph L. Wood, III
					AT&T Information Systems
					Laboratories, Holmdel
					(201) 834-3759
					ariel!jlw

preece@ccvaxa.UUCP (02/25/85)

>    >To exchange two items without an intermediate variable, try:
>    > 	b ^= a ^= b ^= a
>    > [and so on and so on]

>    Who cares?  The xor trick may be cute, but if any programmer that works
>    for me tries to put that kind of crap in his code to make it run faster,
>    s/he should probably start looking for another job.  Can we move this to
>    net.lang.c.worthless.trivia?
------------
It's silly to beat dead horses like the need for making programs run faster;
if you have things where making things run a little faster will make them
viable, you know the need, if you can live with things written well and
not polished for speed, you're probably better off.

The argumentative tone is a little much, though.  The xor trick isn't that
obscure and it's compact, so that attaching a simple comment explaining
what's happening should be sufficient to make it acceptable.

scott preece
gould/csd - urbana
ihnp4!uiucdcs!ccvaxa!preece