[comp.lang.c] Parenthesis in macros

leo@philmds.UUCP (Leo de Wit) (07/16/88)

In article <2089@ssc-vax.UUCP> dmg@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).