C Quirk??

Matt Landau mlandau at bbn.com
Thu Feb 18 06:14:01 AEST 1988


In comp.lang.c (<413 at fig.bbn.com>), rsalz at bbn.com (Rich Salz) writes:
>
>As a general rule, you probably don't want to use { } in #define's
>as  { }; is not the same as { }.

One trick that works really nicely is:

	#define COMPLEX_MACRO()	    do {statement-group} while (0)

Since "do {} while (0)" is a single statement, you can nest this
inside if's without worrying about getting the nesting wrong, missing
or extra semicolons (you just always follow the invokation with one,
just as though it were a function call), etc.  

It's guaranteed that the statement-group will be executed exactly once, 
and any compiler worth its salt will figure out that it can eliminate 
the test and generate the equivalent of inline code.

Of course, lint complains bitterly, but you can't have everything.
--
 Matt Landau			Waiting for a flash of enlightenment
 mlandau at bbn.com			  in all this blood and thunder



More information about the Comp.lang.c mailing list