Is this swap() macro correct?

Michael Meissner meissner at curley.osf.org
Fri Jan 19 09:32:35 AEST 1990


In article <4514 at rtech.rtech.com> mikes at rtech.UUCP (Mike Schilling) writes:

>In fact why use the do-while at all, and why use pointers?  The classic swap
>macro is
>
># define swap(x, y, typ) 	\
>	{			\
>		typ tmp; 	\
>				\
>		tmp = y; y = x; x = tmp;	\
>	}
>
>Is this just as good, or am I being *exceptionally* dense today?

In terms of while the do/while(0), it is to support using the swap
macro in an if statement.  Consider the following fragment:

	if (condition)
		swap (a, b, int);
	else
		flag = TRUE;


If the macro is defined as above, the ';' after the macro invocation
will be treated as an empty statement, and the else will generate a
compiler error.  The do { ... } while (0) trick allows the ';' to
properly end the statement.  I originally wondered why the source to
GNU C used this construct, until I realized about else statements.
Michael Meissner	email: meissner at osf.org		phone: 617-621-8861
Open Software Foundation, 11 Cambridge Center, Cambridge, MA

Catproof is an oxymoron, Childproof is nearly so



More information about the Comp.lang.c mailing list