Reputation: 11515
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?
Upvotes: 3
Views: 400
Reputation: 838086
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
Upvotes: 7
Reputation: 3664
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.
Upvotes: 1