位运算符优先级
我在类 C 语言中遇到过几次的问题是:
original | included & ~excluded // BAD
由于优先级,它解析为:
original | (included & ~excluded) // '~excluded' has no effect
有谁知道按位的三个独立优先级的原始设计决策背后是什么?运营商?更重要的是,您同意这个决定吗?为什么?
A gotcha I've run into a few times in C-like languages is this:
original | included & ~excluded // BAD
Due to precedence, this parses as:
original | (included & ~excluded) // '~excluded' has no effect
Does anyone know what was behind the original design decision of three separate precedence levels for bitwise operators? More importantly, do you agree with the decision, and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
至少从 C 起,运算符就具有此优先级。
我同意这个顺序,因为它与它们最相似的算术运算符(
+
、*
和否定)的相对顺序相同。您可以在这里看到
&
与*
以及|
与+
的相似之处:按位非的相似性和否定可以通过以下公式看出:
The operators have had this precedence since at least C.
I agree with the order because it is the same relative order as the relative order of the arithmetic operators that they are most similar to (
+
,*
and negation).You can see the similarity of
&
vs*
, and|
vs+
here:The similarity of bitwise not and negation can be seen by this formula:
为了扩展 Mark Byers 的答案,在布尔代数(电气工程师广泛使用来将逻辑电路简化到最少的门数并避免竞争条件)中,传统是按位 AND 优先于按位 OR。 C只是遵循这个既定的传统。请参阅http://en.wikiversity.org/wiki/Boolean_algebra#Combining_Operations:
To extend Mark Byers' answer, in boolean algebra (used extensively by electrical engineers to simplify logic circuits to the minimum number of gates and to avoid race conditions), the tradition is that bitwise AND takes precedent over bitwise OR. C was just following this established tradition. See http://en.wikiversity.org/wiki/Boolean_algebra#Combining_Operations :