Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 839
Alex Avatar asked Dec 05 '25 10:12

Alex


1 Answers

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

The only case when the standard requires a diagnostic message (note that the standard does not distinguish between warnings and errors that halt the compilation) is when the program violates the standard. Except when the compiler is excempt from that with wording "no diagnostic required".

All other warnings are optional for the compiler and not required by the standard.


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

No, because the parentheses are not required. The warning is just a suggestion by the compiler. The program is well-formed.

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

For what it's worth, my GCC warns regardless of the standard argument.


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

The warning itself tells which warning option has enabled it (here is the warning from my GCC):

warning: suggest parentheses around '+' inside '<<' [-Wparentheses]

To disable, you can use the corresponding option to disable it: -Wno-WHATEVER.


Now my statements look really ugly, with 5 or more parentheses floating around them.

I recommend instead to extract the repetitive structure, and reuse a standard algorithm:

std::accumulate(string, string + 4, 0, [](auto sum, auto value) {
    return (sum << CHAR_BIT) + value;
});

Much fewer parentheses :) Note that in C++11 (prior to C++14) you can not use auto as the type of an argument of a lambda. I don't know what types you use.

like image 90
eerorika Avatar answered Dec 08 '25 08:12

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!