Search code examples
c++bit-manipulationoperator-precedence

why does AND in parenthesis evaluate differently than without?


In C++, 4&1 == 0, and 1&1 == 1. However, 4&1 != 1&1 evaluates to 0, instead of 1, yet (4&1) != (1&1) evaluates to 1 as expected. Why is this?


Solution

  • The relational operator != has a higher precedence than bitwise AND &.

    Thus the expression

    4 & 1 != 1 & 1
    

    will be parsed as

    4 & (1 != 1) & 1