简体   繁体   中英

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?

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

this link can help you :

http://en.cppreference.com/w/cpp/language/operator_precedence

precedence

10 & Bitwise AND
11 ^ Bitwise XOR (exclusive or)
12 | Bitwise OR (inclusive or)
13 && Logical AND
14 || Logical OR

this means that '&' is evaluated before '||' .

It's perfectly fine to learn about the precedence of these operators, just out of curiosity. In real life, this code without parentheses to make the intent absolutely clear is just unacceptable.

If the left side of an || has a non-zero value, then the right side isn't evaluated at all. It's guaranteed to be not evaluated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM