首页 > 解决方案 > Unknown behaviour of OR operator in C++

问题描述

I have this code running by chance and when i put anything as the answer it is showing me correct. I know we have to put ans before YES and yay, but this code was compiled too, as i mentioned if i put any word as the input the output is correct:

string ans;
cin >> ans;

if(ans == "yes" || "YES" || "yay") {
    cout << "Correct";
}else {
    cout << "Incorrect";
}

标签: c++logic

解决方案


好的,这是逻辑运算符的优先级(L->R)和关联性:

(((ans == "yes") || "YES") || "yay")

由于 C/C++没有与 Python 不同的链接。

第一个:ans == "yes"->str比较str

第二:bool result of 1st || "YES"-> boolstr比较=总是true"YES"不为空

第三:true || "YES"=总是true

因此,条件将始终为truefor"YES"且不为"yay"null。


推荐阅读