运算符优先级(按位 '&' 低于 '==')
在 C 编程语言中,为什么按位运算符(& 和 |)的优先级低于等号运算符(==)?这对我来说没有意义。
In the C programing language, why do the bitwise operators (& and |) have lower precedence than the equality operator (==)? It does not make sense to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要询问Brian Kernighan或丹尼斯·里奇。
来自论坛帖子运算符优先级:
那么,这可能是一个原因?我猜测,由于存在多层按位优先级(与关系比较不同),因此它是自……永远……存在的,而且从未得到纠正。
You need to ask Brian Kernighan or Dennis Ritchie.
From the forum post Operator precedence:
So, that might be a reason? I'm guessing since there are several layers of bitwise precedence (unlike relational comparisons) that it's cruft that's existed since...forever...and just was never corrected.
对于 Dennis Ritchie 来说也没有意义,回想起来。
&&和||被添加到语言之后 |和 &,并且出于兼容性原因保持优先级。
It doesn't make sense to Dennis Ritchie, either, in retrospect.
&& and || were added to the language after | and &, and precedence was maintained for reasons of compatibility.
对于为什么 K&R 选择他们所做的优先级,我没有权威的答案。一个相当有意义的示例是:
由于这是按位 AND 运算符,因此它使用非短路评估模式,就像
使用非短路 OR 运算符一样。这可能就是为什么他们选择以这种方式设置优先级组,但我同意你的观点,回想起来这似乎不是一个好主意。
I don't have an authoritative answer as to why K&R chose the precedence they did. One example that makes a fair amount of sense would be this one:
Since this is the bitwise AND operator, it uses a non-short-circuiting evaluation mode, as would
use the non-short-circuiting OR operator. This is probably why they chose to have the precedence group this way, but I agree with you that in retrospect it doesn't seem like a good idea.