c++compiler-errorsbitwise-operatorsbit-shiftoperator-precedence

Shift "<<" and bitwise "&" operators precedence issue. Why it doesn't compile?


This code doesn't compile.

It seems like the compiler (VS) is interpreting the expression as:

(std::cout << ul1) & (ul2 << std::endl)

#include <iostream>

int main() {

  unsigned long ul1 = 7, ul2 = 3;
  std::cout << ul1 & ul2 << std::endl;

  return 0;
}

Compiler errors:

error C2563: mismatch in formal parameter list
error C2568: '<<': unable to resolve function overload

When I explicitly parenthesize (ul1 & ul2), the code compiles.

Why does the compiler not respect the precedence of the & operator being higher than the << operator?


Solution

  • In your case the usage of << corresponds to Bitwise left shift and right shift.

    As you can see in the C++ Operator Precedence, it has higher precedence (number 7) than Bitwise AND (number 11) - which is used in ul1 & ul2.

    Therefore without using parenthesis ((ul1 & ul2)), the 2nd half of the bitwise AND (&) expression is interpreted as: ul2 << std::endl, and an unsigned long does not support shifting with std::endl as an argument.
    This is the cause of the compilation error you get.