Search code examples
c++11gccparenthesesoperator-precedencesuppress-warnings

When does C++11 give warnings about operator precedence?


When writing code, for a long time I knew that && has higher precedence than ||; however, compiling it using the C++11 standard gave me a warning that I should now use parentheses when using both in a single statement.

Now I got a warning that combining >> and + also should have parentheses. Now my statements look really ugly, with 5 or more parentheses floating around them.

1) Is there a resource that says which combinations of operators now require parentheses?

2) Is there a way to silence just the operator precedence warnings, but to keep the other warnings?

Compiler gcc with flags -O2 -Wall -g

The warnings came in when I added the flag -std=c++11

Sample expression:

(((string[0] << CHAR_BIT) + string[1] << CHAR_BIT) + string[2] << CHAR_BIT) + string[3];

Solution

  • See the gcc manual:

    -Wparentheses

    Warn if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about.

    Also warn if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1 : 0) <= z, which is a different interpretation from that of ordinary mathematical notation.

    Also warn for dangerous uses of the GNU extension to ?: with omitted middle operand. When the condition in the ?: operator is a boolean expression, the omitted value is always 1. Often programmers expect it to be a value computed inside the conditional expression instead.

    (I added the emphasis)

    To turn this behavior off, specify -Wno-parentheses to gcc/g++.