C++ 中“OR”和“AND”运算中 if 语句中的多个条件

0 c++ logic if-statement multiple-conditions

我对“if”语句中的“or”和“and”操作有点困惑。在此if(condition_1 || condition_2)操作中,当 OR 运算符检查两个条件及其检查它们的行为时。同样if(condition_1 && condition_2)在此操作中,当 && 运算符检查条件及其检查条件的行为时。

“OR”和“AND”运算如何检查两个或多个条件?

Ted*_*gmo 5

||/or&&/and在 C++ 中所做的事情与在口语中几乎相同 - 但有一个重要的区别。它们是短路的,这意味着,如果已经可以推断出结果,它们就不会“聆听”其余部分。

if (This or That or Titt or Tatt) {
   make something happen
}
Run Code Online (Sandbox Code Playgroud)

如果This就足够了,程序将得出结论:是的,它会让某些事情发生。

if (This and That and Titt and Tatt) {
   make something happen
}
Run Code Online (Sandbox Code Playgroud)

如果Thisfalse就足够了,程序将得出结论:不,它不会使某些事情发生。


就像在口语中一样,您可以设置更复杂的条件来允许某些事情发生:

if ( (This or That) and (Titt or Tatt) ) {
    make something happen
}
Run Code Online (Sandbox Code Playgroud)

意义

  • 要么This或者That必须是true
    并且也
  • 要么Titt或者Tatt必须是true

上式可以写成:

if      (This and Titt) make something happen
else if (This and Tatt) make something happen
else if (That and Titt) make something happen
else if (That and Tatt) make something happen
else                    nope
Run Code Online (Sandbox Code Playgroud)