swap(x,y)
David Johnson x4-6506
davej at mrsvr.UUCP
Wed Aug 23 05:24:00 AEST 1989
>From article <MYwDEFy00WB842JEUx at andrew.cmu.edu>, by tg1e+ at 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.
More information about the Comp.lang.c
mailing list