为什么这段代码有两个不同的输出(GCC 4.5.1)(我评论过重要的一行):
int main()
{
bool a = 1;
bool b = 1;
bool c = 1;
bool a_or_b = (a || b);
bool not_a_or_b = !a_or_b;
bool not_a_or_b__c = not_a_or_b || c;
cout << "(a || b): " << (a || b) << '\n';
cout << "!(a || b): " << !(a || b) << '\n';
cout << "!(a || b) || c: " << (!(a || b)) || c << '\n';//HERE I'M GETTING 0 (incorrectly I would say)
cout << "bool vars:\n";//WHY THIS LINE IS PRINTED AFTER THE PREVIOUS LINE BUT NOT BELOW IT?
cout << "(a || b): " << a_or_b << '\n';
cout << "!(a || b): " << not_a_or_b << '\n';
cout << "!(a || b) || c: " << not_a_or_b__c << '\n';//HERE I'M GETTING 1
return 0;
}
答案 0 :(得分:12)
这是因为<<
的优先级高于||
。使用括号对其进行分组。
cout << "!(a || b) || c: " << ((!(a || b)) || c) << '\n';
// ^ ^
答案 1 :(得分:4)
它解释
(!(a || b)) || c << '\n'
作为
(!(a || b)) || (c << '\n')
答案 2 :(得分:2)
更改此部分:
<< (!(a || b)) || c << '\n'; //interpreted as (!(a || b)) || (c << '\n')
到此:
((!(a || b)) || c) << '\n'; //interpreted as intended!
答案 3 :(得分:0)
这是一个钳位问题
你使用(!(a || b))|| c第一部分是0肯定也许解释者甚至不看[|] c部分。