Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!rutgers!iuvax!purdue!mentor.cc.purdue.edu!l.cc.purdue.edu!cik From: cik@l.cc.purdue.edu (Herman Rubin) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Summary: Useful in managing registers Message-ID: <1524@l.cc.purdue.edu> Date: 22 Aug 89 13:32:07 GMT References: Organization: Purdue University Statistics Department Lines: 32 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 As a function call, it is not worth while. But 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 /* begin swap */ temp = y; y = x; x = temp; /* end swap */ except that if x and y are the same, the second will work but not the first. -- Herman Rubin, Dept. of Statistics, Purdue Univ., West Lafayette IN47907 Phone: (317)494-6054 hrubin@l.cc.purdue.edu (Internet, bitnet, UUCP)