Calling multiple functions in a macro.

Richard A. O'Keefe ok at quintus.uucp
Wed Nov 2 18:35:51 AEST 1988


In article <7462 at ihlpl.ATT.COM> knudsen at ihlpl.ATT.COM (Knudsen) writes:
>In article <353 at marob.MASA.COM>, daveh at marob.MASA.COM (Dave Hammond) writes:
>> #define FOO()	do { foo1(); foo2(); foo3() foo4(); } while(0)
>Why use the do and while?  C has [compound statements], you can say just plain
>	{foo1(); ... foo4();}

Answer: so you can write if (test) foo(); else baz();
With Hammond's definition, the expansion is
	if (test) do { ... } while (0); else baz();
which is valid.  With Knudsen's definition, the expansion is	
	if (test) { ... } ; else baz();
which is **not** syntactically valid.  

If you want a macro to be usable as an expression, use (...)
If you want a macro to be usable as a statement, use do { ... } while (0)

If C had remained syntactically closer to BCPL and copied less of PL/I's
syntactic arsenic, we'd have been spared a fair bit of irritation.



More information about the Comp.lang.c mailing list