Parenthesis in macros (was Re: Unnecessary Parenthesis)

Leo de Wit leo at philmds.UUCP
Sat Jul 16 17:41:12 AEST 1988


In article <2089 at ssc-vax.UUCP> dmg at ssc-vax.UUCP (David Geary) writes:
>"Unnecessary" parenthesis are something I use all the time in macro
>definitions, also.  Consider:

  [example with bad macros deleted]...

>The above two macros should have been written like:
>
>#define Square(x)       (x)*(x)
>#define GetNextChar(c)  (c = getchar())
>
>And now, everything will work as expected.  The moral of the story is:
>
>1)  I always put parenthesis around all tokens in macros.
>2)  I always put parenthesis around the entire macro definition.

No, you don't! Close but no cigar.
The first macro violates 2) and the second one 1). And you can have trouble:
consider !Square(0). You would expect 1, not? A pity, because the precedence
of ! is higher than *, the expression becomes ! (0)*(0) or 1 * 0 or 0.
Also the second can lead to trouble, although you have to do some odd stuff
( consider GetnextChar(p = q) which has a different result in q depending
on whether or not you parenthesize (?) the token in the macro).

>Sometimes, of course, the parenthesis are unnecessary, but it sure helps
>eliminate some nasty bugs.

Indeed. So stick to your own rules.

     Leo.

               (Macro programmers do it all the time).



More information about the Comp.lang.c mailing list