Search code examples
c++bitwise-operatorslogical-operatorsoperator-precedence

C++ Operator precedence for Bitwise AND and Logical OR


From this page, I got to know that operator precedence of Bitwise AND is higher than Logical OR. However, the following program gives an unexpected output.

#include<iostream>
using namespace std;

int main()
{
int a = 1;
int b = 2;
int c = 4;

if ( a++ || b++ & c++)
{
    cout <<a <<" " << b <<" " << c <<" " <<endl;
}
return 0;
}

The output is

 2 2 4

This means that logical OR works first. Does this mean that the operator precedence rule is violated here?


Solution

  • Precedence just means that the expression is written as below

      ( (a++ || (b++ & c++)))
    

    Once you do that, short circuiting means that just the first expression is evaluated.

    This is why a = 2 but b and c are unchanged.

    codepad