C 的传统:按位运算符与相等运算符优先级
我曾经遇到过使用按位运算符的 JavaScript 情况。从逻辑上讲,按位运算符应具有比相等运算符更高的优先级,例如
if val & 10 == 10
alert('flag set')
,但看起来此代码将以另一种方式工作,就像在 JavaScript 中按位运算符的优先级低于相等运算符一样(请参阅 Mozilla 的 JS 参考)。 对于任何有效的数值 val,上面的代码总是返回 0
,因为 val & 的结果是
为 0
。 true0
。因此,正确的方法是在按位表达式周围加上括号:
if (val & 10) == 10
alert('flag set')
我挖掘了问题的历史,似乎这种行为来自 K&R 的 C 时代,其中逻辑 &&
和 ||
运算符添加在按位运算符之后。 就 C 语言的逻辑陈述而言:
if (x == 1 & y == 0) {
/* ... */
}
完全有道理。但它在按位逻辑方面没有任何作用。
C++、Java、Objective-C、PHP、C# 以及最后的 Javascript 都有相同的方式。 Python、Ruby、Go 则相反。
您是否知道有什么原因(除了来自 C 继承的原因)使得编程语言的设计者遵循 C 的优先规则?
I've stumbled in a JavaScript situation where bitwise operators were used. Logically, a bitwise operator should have a higher precedence than an equality operator, e.g.
if val & 10 == 10
alert('flag set')
But it looks like that this code would work the other way, as in JavaScript bitwise operators have lower precedence than equality operators do (see Mozilla's JS reference).
The code above would always return 0
for any valid numerical val, because the result of val & true
is 0
. So, the proper way would be to put parenthesis around bitwise expression:
if (val & 10) == 10
alert('flag set')
I dug up the history of the question and it seems like this behaviour comes from the age of K&R's C, where logical &&
and ||
operators were added after bitwise ones.
In terms of logical statement in C:
if (x == 1 & y == 0) {
/* ... */
}
Makes perfect sense. But it doesn't make any in terms of bitwise logic.
C++, Java, Objective-C, PHP, C# and finally Javascript have it the same way.
Python, Ruby, Go have it the other way around.
Do you know any reasons (apart from the one that comes from C's heritage) which made programming languages' designers to follow C's precedence rules?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论