Search code examples
language-designbitwise-operatorsoperator-precedence

Bitwise operator predence


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?


Solution

  • 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