swap(x,y)

Jon Doran/60000 jon at shaffer.UUCP
Fri Aug 25 01:01:04 AEST 1989


In article <MYwDEFy00WB842JEUx at andrew.cmu.edu>, tg1e+ at andrew.cmu.edu (Timothy R. Gottschalk) writes:
> 
>        To swap two variables x,y in C without using a temporary variable:
> 
>        /* begin swap */
>        x += y;
>        y = x - y;
>        x -= y;
>        /* end swap */

I don't know about that, seems that overflow is a possibility...

Something that I've used (mainly in assembly code) is:
	x ^= y;
	y ^= x;
	x ^= y;

To verify that the above works (x and y must be the same size of a variable...)
choose appropriate values for x and y, represent these in binary on paper,
then perform the exclusive ors manually.  This is perhaps the best explaination.



Jon Doran
IBM AWD,  Austin TX



More information about the Comp.lang.c mailing list