Multiple statements in C macros: C style suggestion

toma toma
Tue Jan 4 13:02:33 AEST 1983



Multiple statements in C macros are really not as bad as all that - 
granted, the following fails miserably:

#define groucho { statement_1 ; statement_2 ; }

	o
	o
	o

    if ( boolean )
	groucho ;
    else
	statement_3 ;


since it results in an else without if.  I submit, however, that the
above is poor style - not because there are multiple statements in the
macro, but because the if is used without braces.  Yes, I know C
is supposed to allow single-line statements without the need for braces;
however, this form has several serious deficiencies:

1.	If "boolean" is several lines long (not entirely uncommon), it
is somewhat tedious to search for the closing parenthesis - it is much
easier to visually scan for the bracket.  In code that already has the
correct indentation, this is not a valid complaint - however, code in
the process of being typed in or edited by someone with not-so-magic
fingers can go through meta-stable states where it is scattered all over
the screen.

2.	Associating braces with any of the conditionals (if, else, 
while, etc.)  makes it crystal clear what is intended.  This eliminates the
ambiguity that can occur without them (reference pg. 52 of "The
C Programming Language").

3.	Vicious side effects (like the above) can occur with macros.
I really don't know if there are any other significant problems that
can occur in this same vein, and I have no intention of finding out.

I submit, then, that the comma operator is not the solution; rather, 
the solution is to write code with rigorous inclusion of braces:

#define harpo { statement_1 ; statement_2 ; }

	o
	o
	o

    if ( boolean ) {
	harpo ;
    }
    else {
	statement_3 ;
    }

				Tom Anderson
				John Fluke Mfg. Co., Inc.
				Everett, Wa.
    



More information about the Comp.lang.c mailing list