Confusing operator precedence: a << b + c << d

冷暖自知 提交于 2019-12-02 06:50:16

问题


Operator + has higher precedence than << in C++, which would mean that expression a << b + c << d should be evaluated as:

a << (b + c) << d

But that does not make sense. More sense can be obtained when following

a << (b + (c << d))

But that violates precedence of the + over <<, doesn't it? How do compilers evaluate the "does makes sense" part?

UPDATE: When asking the question I thought that second variant is used by the compiler, which is why I wondering how did the compiler come to this evaluation. In fact, first one is used and it's the correct one.


回答1:


"Makes sense" is subjective. Which is why compilers don't evaluate "sense", but a grammar based on a set of rules. Becuase << has higher precedence (which is given by those set of rules), it evaluates the expression as

 a << (b + c) << d

When in doubt, use parenthesis.




回答2:


Compilers do not make any account for what makes sense. They simply follow rules.

It's the designers of the languages that make the rules and they generally try to make those rules so that they make sense. Of course, what seems sensible to one person, appears bizarre to another. There's really no way around that.




回答3:


operator << has lower precedence than operator +. See wikipedia.

Compilers don't try to understand if anything makes sense. They just follow the rules of the grammar. To truly know why shift left has been given lower priority than plus, you should probably ask Dennis Ritchie's ghost.

Aside from that, if a grammar wanted to give precedences as you want, it should have made shift left and plus with the same priority (and left-to-right associativity).

However, if you think of such a use case:

unsigned int a, b, mid;
...
mid = a + b >> 1;

then it perfectly makes sense to calculate a + b first. So I think originally when C was designed, they decided shifting comes after common mathematical arithmetic.


In C++, this even makes things more comfortable. The way it is now, you can write:

cout << a + b << endl;

without the need for parentheses. Although this is just a happy coincidence and wouldn't have anything with the original reason for these precedences.




回答4:


In this case compiler seeks for the highest precedence operator and calculates corresponding operation. It hits + and sum b & c. Then remains two << operators and compiler processes them sequentially



来源:https://stackoverflow.com/questions/15953184/confusing-operator-precedence-a-b-c-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!