Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!linus!philabs!cmcl2!seismo!lll-crg!caip!princeton!allegra!alice!ark From: ark@alice.UucP (Andrew Koenig) Newsgroups: net.lang.c Subject: Re: swap() macro Message-ID: <5688@alice.uUCp> Date: Sun, 22-Jun-86 10:27:11 EDT Article-I.D.: alice.5688 Posted: Sun Jun 22 10:27:11 1986 Date-Received: Tue, 24-Jun-86 03:30:57 EDT References: <370@anasazi.UUCP> Organization: Bell Labs, Murray Hill Lines: 44 > #define swap(x, y) \ > if (1) \ > { \ > register int *xp, *yp, t; \ > xp = &(x); \ > yp = &(y); \ > t = *xp; \ > *xp = *yp; \ > *yp = t; \ > } \ > else > > -------------------------------- > > The "if (1) ... else" allows the user to put a semicolon after the macro > invocation, and makes code such as > > if (today == tuesday) > swap(*a++, *b++); > else > swap(*c++, *d++); > > work correctly. On the other hand, if you forget a semicolon: if (x < y) swap (x, y) printf ("%d %d\n", x, y); you will spend a long time wondering why it doesn't print anything. Of course, if you write in C++, you can say: inline void swap (int& x, int& y) { register int t = x; x = y; y = t; } and be done with it. It's a true function, the compiler checks types for you, you can define several swap functions for different types, and so on.