Do I need to use double parenthesis within if statements?

I've seen different practices done by people writing C++ code. Which is right and does it make a big difference?

1
2
3
  if (varOne > varTwo && varOne > varThree)

  if ((varOne > varTwo) && (varOne > varThree))
Use extra parentheses if doing so would make the intent clearer to those who would be reading the code. It depends on the target audience.

Kernighan and Pike in 'The Practice of Programming' suggests: "when mixing unrelated operators, though, it's a good idea to parenthesise."

Parenthesize to resolve ambiguity.
Parentheses specify grouping and can be used to make the intent clear even when they are not required. The inner parentheses in the previous example are not necessary, but they don't hurt, either. Seasoned programmers might omit them, because the relational operators (< <= == ! = >= >) have higher precedence than the logical operators (&& and I I ).

When mixing unrelated operators, though, it's a good idea to parenthesise. C and its friends present pernicious precedence problems, and it's easy to make a mistake.
Last edited on
+1

I always use parentheses to make my intent clear, and to avoid the aforementioned pernicious precedence problems (which have bitten me whenever I didn’t use them).

IMO, the second statement is easier to read than the first anyway.
Topic archived. No new replies allowed.