Unnecessary Parenthesis

David Geary dmg at ssc-vax.UUCP
Thu Jul 14 02:51:20 AEST 1988


In article <175 at lakart.UUCP>, David Goodenough writes:

>
>	if ((a == 1 && b == 2) || (c == 3 && d == 4))
>	
>	if (a == 1 && b == 2 || c == 3 && d == 4)
>
>In the first case, my intention is much clearer (to myself included).
>
>I believe (as do many others) that parentheses serve a double function:
>overriding the normal precedence of operators, AND making things readable.

"Unnecessary" parenthesis are something I use all the time in macro
definitions, also.  Consider:

#define Square(x)  x*x
#define GetNextChar(c)  c = getchar()

main()
{
  int  x=2, i=0;
  char ch;
  char string[100];

  while(GetNextChar(ch) != '\n')
    string[i++] = ch;

  printf("Square of 3 is:  %d\n", Square(x+1));
  printf("String is %s\n", string);
}

1)  The string is never read in, because the while statement expands to:

    while(ch = getchar() != `\n`)

    != has precedence over =, so the character is read by getchar(), then
    it is compared to '\n'.  If the character was a newline, ch gets assigned
    the value 1, if the character was not a newline, then it gets assigned
    the value 0. (NULL ?? ;-))

2)  Square(x+1) expands to:  x+1*x+1 which is: x+x+1.  In our case, we get:
    Square of 3 is:  5.

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.

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


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~	"...Raven hair and ruby lips,			~
~	 Sparks Fly from the fingertips..."		~
~							~
~		Witchy Woman, The Eagles		~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ David Geary, Boeing Aerospace,               ~ 
~ Seattle - "THE DRIZZLE CAPITAL OF THE WORLD" ~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



More information about the Comp.lang.c mailing list