Swapping two variables in place

Dan Bernstein brnstnd at kramden.acf.nyu.edu
Sat Sep 22 16:40:20 AEST 1990


In article <26101 at shamash.cdc.com> awm at shamash.UUCP (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

Is this in the FAQ list? That swap is slow, ugly, and won't work for
pointers or floats on any machine.

The best truly portable inline replacement for void swap(a,b) float *a;
float *b; { float t = *a; *a = *b; *b = t; } is

  #define swap(a,b) do { float *swap_a = a; float *swap_b = b; float \
  swap_t = *swap_a; *swap_a = *swap_b; *swap_b = swap_t; } while(0)

which will fail only if any swap_* is defined as a macro. You can, of
course, generalize this into swap(a,b,type).

If you have a swap that is unsafe or uses its arguments by reference,
please obey convention and give it an upper-only name like SWAP.

---Dan



More information about the Comp.lang.c mailing list