Bitwise operator predence

梦想的初衷 提交于 2019-12-07 12:35:38

问题


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?


回答1:


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:

A  B | A&B A*B | A|B A+B 
0  0 |  0   0  |  0   0
0  1 |  0   0  |  1   1
1  0 |  0   0  |  1   1
1  1 |  1   1  |  1   2

The similarity of bitwise not and negation can be seen by this formula:

~A = -A - 1



回答2:


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 :

Just as in ordinary algebra, where multiplication takes priority over addition, AND takes priority (or precedence) over OR.



来源:https://stackoverflow.com/questions/3730539/bitwise-operator-predence

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