Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!cs.utexas.edu!uunet!emtek!steveh From: steveh@emtek.UUCP (Steve Hollasch) Newsgroups: comp.lang.c Subject: Re: Using macros as statements (Re: Typeof operator in C) Summary: Function-Like Macro Definitions Keywords: macro statement Message-ID: <90@emtek.UUCP> Date: 20 Jan 90 19:15:10 GMT References: <16678@megaron.cs.arizona.edu> <7106@tank.uchicago.edu> <19840@watdragon.waterloo.edu> Organization: Emtek Health Care, Inc. Lines: 32 > 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