令人困惑的运算符优先级:<< b + c<< d [英] Confusing operator precedence: a << b + c << d

查看:79
本文介绍了令人困惑的运算符优先级:<< b + c<< d的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运算符+的优先级高于C ++中的<<,这意味着表达式a << b + c << d的求值应为:

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.

推荐答案

理解"是主观的.这就是为什么编译器不评估感觉",而是评估基于一组规则的语法的原因.由于<<具有更高的优先级(由这些规则集提供),因此将表达式的计算结果为

"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.

这篇关于令人困惑的运算符优先级:&lt;&lt; b + c&lt;&lt; d的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆