Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!wasatch!cs.utexas.edu!uunet!mcsun!sunic!sics.se!uplog!uplog.uplog.se!thomas From: thomas@uplog.se (Thomas Hameenaho) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Message-ID: Date: 25 Aug 89 12:16:55 GMT References: Sender: thomas@uplog.UUCP Organization: TeleLOGIC Uppsala AB Lines: 35 In-reply-to: tg1e+@andrew.cmu.edu's message of 22 Aug 89 06:34:57 GMT In article tg1e+@andrew.cmu.edu (Timothy R. Gottschalk) writes: 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 The problem with this is the possible loss of precision. (x += y) must not overflow x. Also if the variables are floating types you could wind up having almost no significant bits left. A solution that doesn't introduce any loss of precision but only works for scalar types is: x ^= y; y = x ^ y; x ^= y; -- Real life: Thomas Hameenaho Email: thomas@uplog.se Snail mail: TeleLOGIC Uppsala AB Phone: +46 18 189406 Box 1218 Fax: +46 18 132039 S - 751 42 Uppsala, Sweden