Using macros as statements (Re: Typeof operator in C)
Scott M. King
smking at lion.waterloo.edu
Wed Jan 17 02:36:19 AEST 1990
In article <721 at eedsp.eedsp.gatech.edu> baud at eedsp.UUCP (Kurt Baudendistel) writes:
:Be careful, however, of the nasty C preprocessor, which will make this
:nice looking and appealing definition:
: #define SWAP(a,b) {typeof (a) tmp; tmp=a; a=b; b=tmp}
:fail in many cases, like
: if (x < y)
: SWAP (x, y); // bracketing of SWAP makes the `;' extraneous
: else // and fatal
: x = y;
:
:Kurt Baudendistel --- GRA
:Georgia Tech, School of Electrical Engineering, Atlanta, GA 30332
:internet: baud at eedsp.gatech.edu uucp: gatech!gt-eedsp!baud
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
)
Scott M. King, Software Devlopment Group, University of Waterloo
More information about the Comp.lang.c
mailing list