首页 > 解决方案 > 等式运算符 == 右侧的按位运算符 ^ 未按预期工作

问题描述

代码片段:

void fn(){
    if(14-2==0^2){
        cout<<"14-2 is "<<14-2<<"\n";
        cout<<"0^2 is "<<(0^2)<<"\n";  //cout<<0^2 shows error: invalid operands of types 'int' and 'const char [2]' to binary 'operator<<'
        cout<<"How is if evaluated to be true?";
    }
    else{
        cout<<"else";
    }
}

输出:
14-2 是 12
0^2 是 2
如果评估为真,如何?

我通过在 () 中包含 0^2 来解决问题,所以如果条件变为

if(14-2==(0^2))

这现在按预期工作。

问题:我想了解为什么如果评估为真

标签: c++

解决方案


operator_precedence

14 - 2 == 0 ^ 2

被解析为

((14 - 2) == 0) ^ 2

如此(12 == 0) ^ 2
如此false ^ 2
如此2(如此true


推荐阅读