Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uunet!munnari.oz.au!goanna!ok From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) Newsgroups: comp.lang.c Subject: Re: Swapping two variables in place Message-ID: <3804@goanna.cs.rmit.oz.au> Date: 24 Sep 90 07:38:43 GMT References: <26101@shamash.cdc.com> Organization: Comp Sci, RMIT, Melbourne, Australia Lines: 24 In article <26101@shamash.cdc.com>, awm@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.