如何将两个if语句合并为一个

How to combine two if statements into one

本文关键字:合并 一个 语句 if 两个      更新时间:2023-10-16

嗨,我有这两个单独的if语句,当这样放的时候;

if (powerlevel <= 0) // <--- ends up having no effect
if (src.health <= 0)
    the_thing_to_do();

如何将这两个if语句合并为一个?有可能吗?如果是,怎么办?

如果希望两个语句都为true,请使用逻辑AND

if(powerlevel <= 0 && src.health <= 0) 

如果您希望任一语句为真,请使用逻辑OR

if(powerlevel <= 0 || src.health <= 0) 

以上两个运算符都是逻辑运算符

如果希望同时满足(逻辑AND),请使用operator&&

if(powerlevel <= 0 && src.health <= 0) { .. }

或者operator||,如果你只想满足一个(逻辑or)

if(powerlevel <= 0 || src.health <= 0) { .. }

这取决于您是否希望两者都求值为true。。。

if ((powerlevel <= 0) && (src.health <= 0)) {
  // do stuff
}

或者至少一个。。。

if ((powerlevel <= 0) || (src.health <= 0)) {
  // do stuff
}

区别是逻辑AND(&&)或逻辑or(||)

如果它是有意义的(有时),那么它只是一个aternative。

Both true:
if (!(src.health > 0  || powerlevel > 0)) {}
at least one is true:
if (!(src.health > 0  && powerlevel > 0)) {}

或者如果您不想使用&amp;你可以使用三元算子

#include <iostream>
int main (int argc, char* argv[])
{
  struct
  {
      int health;
  } src;
  int powerlevel = 1;
  src.health = 1;
 bool result((powerlevel <= 0) ? ((src.health <=0) ? true : false)  : false);
 std::cout << "Result: " << result << std::endl;
}