Swapping two variables in place

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Mon Sep 24 17:38:43 AEST 1990


In article <26101 at shamash.cdc.com>, awm at shamash.cdc.com (Allan Magnuson) writes:
> There was a message a while back about not being able to create a good
> #define function to swap two variables.
> 
> How about this one: #define swap(a,b) a^=b^=a^=b

Hmm, let's see:
	double x, y;	swap(x, y);	Drat!
Try again:
	char *x, *y;	swap(x, y);	Drat!
Easy one:
	int i;		swap(i, i);	Drat! (i becomes 0)

Using a GCC extension, we can do

#define swap(x,y) do {typeof(x) ZZT = (x); (x) = (y); (y) = ZZT;} while (0)

which works in a lot of cases, but has problems of its own.
For example, swap(*p++, *--q);

For the record, the version using assignments is often *faster* than
the XOR-based version, as well as being more generally applicable.
-- 
Heuer's Law:  Any feature is a bug unless it can be turned off.



More information about the Comp.lang.c mailing list