Using Macros

Stephen Clamage steve at taumet.com
Fri Aug 10 01:13:30 AEST 1990


ok at goanna.cs.rmit.oz.au (Richard A. O'Keefe) writes:

>>  [asks about defining macros that expand to more than one statement]

>I wasn't going to reply to this, but the Official Free Answer[*] is
>to use the expansion
>	do { /* your statements go here */ } while (0)
>This will work in any context where a statement is allowed; it wants
>a semi-colon after it just like a simple function call would.

But doesn't work in expression contexts.  One of the many problems
("gotchas") with macros is that while it may look like a function
call, it may not be.  If we have a macro
	#define foo(a, b) do { ........... } while (0)
there is a temptation to use it like
	m = k + foo(i, j) / n;
The compiler will reject this with an error message which may be hard to
relate to the code as written.

On that basis, I prefer a macro written as an expression, where possible.
Use comma-expressions, and enclose the whole thing in parens.
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list