打印以相反顺序写入的表达式时获得不同的结果

k1g*_*abi 2 c++ operator-precedence

为什么我在第3行得到不同的结果?输出是:

1
1
0
1
Run Code Online (Sandbox Code Playgroud)

我不应该收到行号.3还输出1而不是0?它具有与其他行相同的语法.

#include <iostream>
using namespace std;

int main()
{
    int x = -3;
    bool a = (x % 2 == 1) || (x < 0);
    bool b = (x < 0) || (x % 2 == 1);
    cout << a << "\n";                              // line 1
    cout << b << "\n";                              // line 2
    cout << (x % 2 == 1) || (x < 0); cout << "\n";  // line 3
    cout << (x < 0) || (x % 2 == 1); cout << "\n";  // line 4
}    
Run Code Online (Sandbox Code Playgroud)

Log*_*uff 10

由于运算符优先级,它operator<<高于operator||,只有

(x % 2 == 1)
Run Code Online (Sandbox Code Playgroud)

部分印刷.剩下的就像在做cout || (x < 0);.(请注意std::cout,与任何其他std::basic_ios派生流一样,可以隐式转换为bool)

使用括号,它看起来像这样:

(cout << (x % 2 == 1)) || (x < 0);
Run Code Online (Sandbox Code Playgroud)

第4行打印1,因为(x < 0)是真的,你切换了操作数 - 现在应该很清楚了.

解决方案:括号operator||调用:

cout << (x % 2 == 1 || x < 0);
Run Code Online (Sandbox Code Playgroud)

operator||另一方面,围绕着操作数的括号是多余的.