Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!hellgate.utah.edu!cs.utexas.edu!uunet!algor2.algorists.com!jeffrey From: jeffrey@algor2.algorists.com (Jeffrey Kegler) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Message-ID: <1989Sep6.061301.17629@algor2.algorists.com> Date: 6 Sep 89 06:13:01 GMT References: <784@skye.ed.ac.uk> <1267@levels.sait.edu.au> <149@cpsolv.UUCP> Reply-To: jeffrey@algor2.UUCP (Jeffrey Kegler) Organization: Algorists, Inc. Lines: 39 One thing that makes A) #define swap(x,y) (x ^= y, x ^= y ^= x) seem more attractive than B) #define swap(x,y) {int tmp; tmp = x; y = tmp; x = y; } is the syntax. Consider if (...) swap(x,y); else { do stuff ...; swap(a,b); } which the Solution A allows, but which won't work with the Solution B, unless the first semi-colon is omitted. The second last semi-colon in the above example is misleading, but overwise harmless. Even more disastrous for B is for (tweedledee=1, tweedledum=0; !done; swap(tweedledee, tweedledum)) { stuff ... Notes: 1) Both solutions are taken from other postings and not tested. 2) Solution A should have more parentheses, they are omitted for clarity. 3) It is assumed all variables are ints. 4) I think the idea of a global temporary to make Solution B an expression is unworkable if your global temporary has its name used elsewhere and ugly when it does work. 5) Defines are prefered because inlining the solutions makes the code harder to read, and the overhead of a function call to swap two ints is often not justifiable. -- Jeffrey Kegler, Independent UNIX Consultant, Algorists, Inc. jeffrey@algor2.ALGORISTS.COM or uunet!algor2!jeffrey 1762 Wainwright DR, Reston VA 22090