using ^= to swap two integers
Arnold Robbins
arnold at gatech.UUCP
Sat Feb 9 07:18:56 AEST 1985
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 at gatech ARPA: arnold%gatech.csnet at csnet-relay.arpa
UUCP: { akgua, allegra, hplabs, ihnp4, seismo, ut-sally }!gatech!arnold
Help advance the state of Computer Science: Nuke a PR1ME today!
More information about the Comp.lang.c
mailing list