Using Macros

Stephen Carlson scc at rlgvax.UUCP
Sat Aug 11 10:01:26 AEST 1990


In article <3526 at goanna.cs.rmit.oz.au> ok at goanna.cs.rmit.oz.au (Richard A. O'Keefe) writes:
>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.

Another way is:
	if (1) { /* your statements go here */ } else

This is just as valid as the do { ... } while(0) trick.  The semicolon would
terminate the else with a null statement, and the else avoids a dangling else
problem:
	if (cond)
		if (1) { ... } else ;
	else
		...

As a matter of style, I prefer to define statement-like macros that have no
arguments with an empty set of parenthesis:
	#define FOO() if (1) { int a; bar(&a); } else
and invoke it with
	FOO();
anywhere a statement is valid.  This has more of the feel of a function
call.  Although this works (a #define with 0 arguments) with every
preprocessor I've ever used, is there any official sanction for this
construct?
-- 
Stephen Carlson            | ICL OFFICEPOWER Center
scc at rlgvax.opcr.icl.com    | 11490 Commerce Park Drive
..!uunet!rlgvax!scc        | Reston, VA  22091



More information about the Comp.lang.c mailing list