Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.csd.uwm.edu!bionet!ames!purdue!haven!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Message-ID: <19211@mimsy.UUCP> Date: 22 Aug 89 14:25:22 GMT References: <1524@l.cc.purdue.edu> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 32 Before anyone charges off to `correct' Herman Rubin.... (Note: I have compressed these vertically and elided some text.) In article tg1e+@andrew.cmu.edu (Timothy R. Gottschalk) writes: >>To swap two variables x,y in C without using a temporary variable: >> x += y; y = x - y; x -= y; In article <1524@l.cc.purdue.edu> cik@l.cc.purdue.edu (Herman Rubin) writes: >... for switching registers in a tights situation on a machine without >instruction overlap, it is likely to be as fast as anything. One needs >three instructions, and since the operations may be as fast as moves, >no time is lost, compared to > > temp = y; y = x; x = temp; > >except that if x and y are the same, the second will work but not the first. Again, before you `correct' this: that is, not that x and y have the same *value*, but rather that x and y name the same storage location: int a = 1, *x = &a, *y = &b; *x += *y; *y = *x - *y; *x -= *y; which winds up setting `a' to 0, rather than swapping it with itself. The xor-trick is more often seen in the `swap registers in a tight situation' situation than the add/subtract trick (it has the advantage of working on two-address machines, as well). -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris