Using Macros

Ken Lerman lerman at stpstn.UUCP
Wed Aug 8 23:22:12 AEST 1990


In article <151 at smds.UUCP> rh at smds.UUCP (Richard Harter) writes:
->If you have a block of statements defined in a macro which you
->wish to use as though it were a function, there are several ways
->to handle it.  Perhaps the clearest is:
->
->#define A_MACRO(args) do {...body...} while(0)
->
->This makes A_MACRO a statement.  This protection is needed when
->you have A_MACRO in an if statement, e.g.
->
->if (foo==bar) A_MACRO(moby);
->else B_MACRO(gumby);
->
->-- 
->Richard Harter, Software Maintenance and Development Systems, Inc.
->Net address: jjmhome!smds!rh Phone: 508-369-7398 
->US Mail: SMDS Inc., PO Box 555, Concord MA 01742
->This sentence no verb.  This sentence short.  This signature done.

IMHO the many responders to this question gave the right answer to
perhaps the wrong question.  The issues is not how to write the macro,
but how to invoke it.

Change:

 if (foo==bar) A_MACRO(moby);
 else B_MACRO(gumby);

To:

 if (foo==bar){ A_MACRO(moby);}
 else {B_MACRO(gumby);}

and the problem goes away.  (Choose your own indenting style.)

Aside:
	The one that really gets me is when someone does:
	foo(gag) and you later discover that foo() is a macro.
	Unfortunately, ANSI C has some of these.  Is there a
	requirement that they are expressions?

Of course, you have to anticipate the possiblity of change when you
write the original code.  And if you are any good, you get it right
the first time :+) I mean :=) I mean :<), well, you know what I mean. :-)

Ken



More information about the Comp.lang.c mailing list