Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!gem.mps.ohio-state.edu!ginosko!uunet!mcsun!hp4nl!botter!star.cs.vu.nl!condict From: condict@cs.vu.nl (medewerker ast) Newsgroups: comp.lang.c Subject: Re: swap(x,y) Message-ID: <3206@ski.cs.vu.nl> Date: 11 Sep 89 11:18:18 GMT References: <784@skye.ed.ac.uk> <1267@levels.sait.edu.au> <149@cpsolv.UUCP> <1989Sep6.061301.17629@algor2.algorists.com> Reply-To: condict@cs.vu.nl (medewerker ast) Organization: VU Informatica, Amsterdam Lines: 34 In article <1989Sep6.061301.17629@algor2.algorists.com> jeffrey@algor2.UUCP (Jeffrey Kegler) writes: |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. As has been described several times in this newsgroup, this defect can be avoided by using one of the following two equivalent definitions instead of (B), above: B1) #define swap(x,y) do {int tmp; tmp = x; y = tmp; x = y; } while (0) B2) #define swap(x,y) if (1) {int tmp; tmp = x; y = tmp; x = y; } else 0 This has the advantage of producing a syntax error if the use of swap is not followed by a ';', just as a real function call would. It has the disad- vantage of looking silly and inefficient to the uninitiated. It should, however, generate the same code as without the extraneous statement, on any reasonable C compiler. Mike Condict condict@cs.vu.nl Vrije University