Search code examples
c++cbitwise-operatorsoperator-precedencecomparison-operators

What is the rationale for == having higher precedence than bitwise AND, XOR, and OR?


In C++, what is the rationale for == and != having higher precedence than bitwise AND, XOR, and OR?

It would seem to me more natural to have operator== and operator!= come after operator&, operator^, and operator|. I'd like to understand the motivation so that I can better remember the ordering.

For example, I would think the following kind of usage would be common:

if (bitFields & value == 0) { // Incorrect test.
  // Do Something.
}

Since the == result is either 1 or 0, why would you ever want to use it for bitwise operations? Instead, the above must be written as:

if ((bitFields & value) == 0) { // Correct test.
  // Do Something.
}

to get the intended meaning where the bitwise AND is done before the comparison to zero.


Solution

    1. It is historical from C
    2. Consider using functions in your if statement

    e.g.

    if (func1() == 2 & func2() == 3)
    

    With the precedence of == being higher that & ensures that both functions are called.