Path: utzoo!utgpu!watserv1!watdragon!lion!smking From: smking@lion.waterloo.edu (Scott M. King) Newsgroups: comp.lang.c Subject: Using macros as statements (Re: Typeof operator in C) Keywords: macro statement Message-ID: <19840@watdragon.waterloo.edu> Date: 16 Jan 90 15:36:19 GMT References: <16678@megaron.cs.arizona.edu> <7106@tank.uchicago.edu> <-K016ODxds13@ficc.uu.net> <721@eedsp.eedsp.gatech.edu> Sender: daemon@watdragon.waterloo.edu Reply-To: smking@lion.waterloo.edu (Scott M. King) Followup-To: comp.lang.c Organization: U. of Waterloo, Ontario Lines: 27 In article <721@eedsp.eedsp.gatech.edu> baud@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@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