[net.unix-wizards] Multiple statements in C macros: C s

johnl (01/06/83)

#R:vax1:-27300:ima:9200002:000:603
ima!johnl    Jan  5 14:48:00 1983

I thought we went through this a month ago.  If you really want to write
macros that act like statements, you write

# define foo if(1) { any; sequence; of; statments; you; want; } else
				/* Note: NO semicolon after the "else" */

	...
	if(something)
		foo;    /* works as desired */
	else
		foo;    /* also works as desired */

Most C compilers with -O are smart enough to generate good code for this.
In my experience, though, multi-statement defines usually are symptomatic
of premature optimization or else badly designed data structures.

John Levine, decvax!yale-co!jrl, ucbvax!cbosgd!ima!johnl

emrath (01/07/83)

#R:vax1:-27300:uiucdcs:13700014:000:400
uiucdcs!emrath    Jan  7 02:48:00 1983

This response is probably unwarranted, but...
the syntax for the if statement is:
	if (expr) statement else statement
If you declare a macro as a compound (or simple, for that matter) statement,
then use it as if it were one. The following prog works just fine, thank you!


	#define groucho  {i++;printf("i=%d\n",i);}
	main(){ int i=0;
	for (;;) if (i < 10) groucho else break;
	printf("blech\n");}

crp (01/12/83)

One place you might easily want to put multiple statments into a macro
is when putting debug or checkout code into a program.
I find that with something like a complex driver it is never the
right time to actually remove any consistency checking code -- but it
is nice to turn it off in "production" versions.
Putting things in #ifdef , #endif  sections in the code is very
messy visually -- whereas putting a macro call
(or more likely, statements as an argument to a macro) isn't distracting
and allows the same freedom to turn on/off code by changing
the macro definition.

chris.umcp-cs@Udel-Relay (03/28/83)

From:  Chris Torek <chris.umcp-cs@Udel-Relay>

,
To: Charles F. Von Rospach <CHUQUI@MIT-MC>y>
        hplabs!hao!cires!nbires!crp@UCB-VAX
Cc: Unix-Wizards@SRI-UNIX
Via:  UMCP-CS; 29 Mar 83 0:10-EST

There is only one problem with debug functions, as opposed to macros:
they're slower.  (Though if memory is more important than speed,
they're usually smaller.)  If the stuff can be conditionally compiled
that's even better.  If you have multi line debug functions, or
functions with variable # of args, you can always do this:

/* if DEBUG, call debugfunc for bugout.  Otherwise, discard all bugouts.
   In either case, generate exactly one statement per bugout. */
#ifdef DEBUG
# define bugout(x) debugfunc x
#else not DEBUG
# define bugout(x)
#endif DEBUG

...
	stmt;
	bugout ( (param1,param2,param3) );
	stmt;
	bugout ( ("got here") );
...

While it looks a bit strange, it works.  (I even just tested it!)
				- Chris