Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.csd.uwm.edu!mrsvr.UUCP From: davej@mrsvr.UUCP (David Johnson x4-6506) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Message-ID: <906@mrsvr.UUCP> Date: 22 Aug 89 19:24:00 GMT References: Sender: news@mrsvr.UUCP Lines: 34 From article , by tg1e+@andrew.cmu.edu (Timothy R. Gottschalk): = = To swap two variables x,y in C without using a temporary variable: = = /* begin swap */ = x += y; = y = x - y; = x -= y; = /* end swap */ = = Just curious...(this looks pretty valid) does anyone know an even = simpler method? I would never program this way -- it's more of a theory = question. I've been told that it can't be done (???). = Tim Gottschalk = Pgh, PA This code should work fine for numeric x,y that aren't TOO large (so that the first line does not cause overflow - though even that may work (depending on your particular compiler)) or for float x,y that are not excessively far apart in precision. If you set x = 1.0e+09 and y = 1.0e-8, the swap code above results in x = 0 and y = 1.0e+09. Also, low-order bits could be lost due to rounding/truncation of float's. A more intriguing (and less obvious) way is to do: /* begin swap */ x ^= y; y ^= x; x ^= y; /* end swap */ Alas, in C, the bitwise OR only works with int's and char's :-(. Of course, you can type-cast, but it doesn't look as neat. Dave Johnson - Computer People Unlimited @ GE Medical Systems.