Using macros as statements (Re: Typeof operator in C)

Steve Hollasch steveh at emtek.UUCP
Sun Jan 21 06:15:10 AEST 1990


> To make a macro behave exactly as a statement, replace the { and } in
> the macro definition with START_MACRO and END_MACRO:
> #define START_MACRO  do {
> #define END_MACRO    } while ( 0 )
> 
> The compiler should catch uses with too few or too many semi-colons here.
> 
> (Note that another version I have seen has very unexpected effects if the
> semi-colon is left off the macro usage:
> #define START_MACRO  if ( 1 ) {
> #define END_MACRO    } else

    I use two basic forms for multi-statement macro definitions, and
ALWAYS terminate a macro invocation with a semi-colon (I think of
macro invocations as inline functions, so this makes sense).

    An alternative method is the following:

#define MACRO(a,b,c) \
(   (a)[0] = (b)[0] + (c)[0],  \
    (a)[1] = (b)[1] + (c)[1],  \
    (a)[2] = (b)[2] + (c)[2]   \
)

    That is, define the macro as a throwaway expression.  This method
seems 'cleaner' to me, since there are no implied tests.  The
trailing-else (or single-loop) method, however, is superior in that
it allows any kind of code within the macro body.  NOTE:  This
includes variable declarations (as in swap routines)!

_______________________________________________________________________________
Steve Hollasch [uunet!emtek!steveh]                              Tempe, Arizona



More information about the Comp.lang.c mailing list