GCC C++ warning: suggest parentheses

1.9k views Asked by At

I've written an expression parser which spits out a bunch of assembler instructions for x86, x64 and ARM.

To test it I've written a small app that generates random expressions, compiles them with GCC and compares the result with my code, so far so good.

Now I want to have my parser produce warnings similar to GCC.

I've noticed that with GCC 5.1.0

    int a = 100 + 100 | 10;

GCC give a suggested parentheses warning around |

but

    int b = 100 * 100 | 10;

GCC gives no warning.

but both addition and multiplication have higher precedence than bitwise OR, so why no warning on the int b = expression?

I'm very tired lol so may have overlooked something.

3

There are 3 answers

0
celtschk On BEST ANSWER

The ultimate answer can only come from the implementers, but I guess the reason is that there are other languages which have different preferences of those operators, and therefore users of those other languages may misinterpret the expression. For example in some Pascal dialects, & has the same precedence as * and | has the same precedence as +, so an expression involving both + and | without parentheses in between may have a different interpretation (standard Pascal has no & or |, but the precedence of and and or in standard Pascal follows the same rules). I guess that just like many languages copy the C operator precedence, others copy the Pascal one.

4
Surt On

This is matter of Precedence, * is priority 5, + is 6 and | is 12.

So when you get a warning from one but not from the other you have found a compiler inconsistency. Or the compiler has a rule that says if (priorityDifference(X,Y) < 7 display parentesis warning, which makes no sense.

Post a bug report against your version.

0
CascadeCoder On

After reading the comment by celtschk, I tried a few expressions in C++ and free pascal

C++

    a = 100 + 100 & 100; // = 64
    a = (100 + 100) & 100; // = 64

Free Pascal

    a := 100 + 100 and 100; // = 200
    a := (100 + 100) and 100; // = 64

Free Pascal

    a := (100 + 100) and 222; // = 200
    a := 100 + 100 and 222; // = 168

// C++

    a = 100 * 100 & 222; // = 16

// Free Pascal

    a := 100 * 100 and 222; // = 16

So it would seem bitwise operators in other languages may not have the same precedence level as in C++, which would cause headaches if translating between languages. Maybe the warning message produced by GCC could be a bit more descriptive.