Boolean Operators Slighted in C (really swap with XOR)

mnl mnl at cernvax.UUCP
Fri May 16 12:11:08 AEST 1986


In article <2741 at utcsri.UUCP> greg at utcsri.UUCP (Gregory Smith) writes:
>In article <602 at brl-smoke.ARPA> rbj at icst-cmr (Root Boy Jim) writes:
>
>>3) Exchange operator. This has probably been discussed before, so pardon
>>	me if I blunder into that pit. BUT, DMR has stated that one of
>>	the reasons that exponentiation was left out was because no
>>	(or few, if any) machine could do it inline, and therefore
>>	all the compiler would be doing is a function call anyway.
>>	By the same reasoning, exchange CAN be done efficiently by
>>	some machines, and the hack of a temporary variable and
>>	three assignments is a rather stale idiom. The three
>>	statement XOR trick avoids the temporary, at the expense
>>	of execution time and clarity.
>>
>Good stuff. Even machines without an EXG can use a scratch register, which
>is better than using a user-supplied temp.
>What, by the way, is the XOR trick?
>
To swap the contents of A and B (no particular language):

A = A XOR B
B = A XOR B
A = A XOR B

On some machines, assuming A and B are in registers, this won't take
any more time than the normal three assignments using a temporary.
-- 
Mark Nelson

mnl at cernvax.bitnet or ...!seismo!mcvax!cernvax!mnl
If the ACM had a sub-group for naturalists, would it be ACM
SIGnature?



More information about the Comp.lang.c mailing list