Is this swap() macro correct?

John S. Price john at stat.tamu.edu
Fri Jan 19 09:00:49 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?

The only problem I see with this, and it's not much of a problem, is
that if you type

swap(x,y,int);

that will be expanded to

{
	int tmp;
	tmp = y; y = x; x = tmp;
};

with a semicolon at the end of the block, which isn't always
wanted.  The reason for the do { ... } while (0) is so that
the semicolon can be put there without any problem.
Most compilers just see the ; as a null statement and ignore it,
anyway, but style wise it's not wanted.

The do {...} while (0) loop is usually recognized by the compiler
as a useless block, and optimized out, so that it doesn't do
the comparison before it exits the block.  It will see the 0 as
always false, and optimize this out.


--------------------------------------------------------------------------
John Price                   |   Morals define our path through life,
john at stat.tamu.edu           |   And everyone's path is different... - Me
--------------------------------------------------------------------------



More information about the Comp.lang.c mailing list