Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!julius.cs.uiuc.edu!rpi!sci.ccny.cuny.edu!phri!cmcl2!kramden.acf.nyu.edu!brnstnd From: brnstnd@kramden.acf.nyu.edu (Dan Bernstein) Newsgroups: comp.lang.c Subject: Re: Swapping two variables in place Message-ID: <19329:Sep2206:40:2090@kramden.acf.nyu.edu> Date: 22 Sep 90 06:40:20 GMT References: <26101@shamash.cdc.com> Organization: IR Lines: 21 In article <26101@shamash.cdc.com> awm@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