swap(x,y)

Kim Letkeman kim at kim.misemi
Fri Sep 1 22:23:52 AEST 1989


> A more intriguing (and less obvious) way is to do:
>   /* begin swap */
>   x ^= y;
>   y ^= x;
>   x ^= y;
>   /* end swap */
> 
> Alas, in C, the bitwise OR only works with int's and char's :-(.               
> Of course, you can type-cast, but it doesn't look as neat.  
> 
> Dave Johnson - Computer People Unlimited @ GE Medical Systems.
> 
I hope that all of this talk about swapping two values without a
temporary is just for fun ...

When one writes clean, easy to read code, this sort of idea never
occurs. Simply using a temporary location makes it obvious what is
going on. It would be silly to have to actually comment something as
trivial as "here I am swapping two values".

It might be said (by the non-enlightened) that "it's only three lines
of code ... surely you can figure out what is going on."

This is true, anyone can figure it out by pausing and examining these
in detail. But if they occur in a program of several hundred, or
thousand lines, they are glossed over without any attempt at
understanding them. A critical point in the algorithm could then be
missed. 

Of course, it is possible that one would do this for efficiency's
sake, right? After all, one less temporary variable *must* be more
efficient.

Well ... not on my machine (sunos 4.0.3). 

Here are two code fragments and their assembly output:

	x ^= y;
	y ^= x;
	x ^= y;

	movl    a6@(-0x8),d0
	eorl    d0,a6@(-0x4)
	movl    a6@(-0x4),d0
	eorl    d0,a6@(-0x8)
	movl    a6@(-0x8),d0
	eorl    d0,a6@(-0x4)

	temp = x;
	x = y;
	y = temp;

	movl    a6@(-0x4),a6@(-0xc)
	movl    a6@(-0x8),a6@(-0x4)
	movl    a6@(-0xc),a6@(-0x8)
	                        
As an exercise, these are mildly interesting, but as a coding style,
they suck.
-- 
Kim Letkeman    uunet!mitel!spock!kim



More information about the Comp.lang.c mailing list