if语句检查每个OR操作符

Does an IF-Statement checks every OR operator?

本文关键字:OR 操作符 语句 检查 if      更新时间:2023-10-16

目前我正在用粒子进行测试,有一个重要的问题。

if (condition a || condition b || condition c)

if(condition a)
        if(condition b)
             if(condition c){
}

哪个更快?

c++使用所谓的短路表达式求值,这意味着一旦遇到决定表达式最终结果的项(不管其余项可能求值为什么),它将停止求值项。

因为不管X的值是多少,TRUE OR X都是TRUE,所以c++不会计算X。

但是,级联的if语句是而不是与第一个表达式等效。它相当于具有多个and而不是多个or的表达式。

这个问题可能已经在其他地方回答过了,但是c++使用短路方法,也就是说,如果任何条件通过,其余的都被忽略(在逻辑或:|的情况下)。

对于逻辑和:&则相反——第一个条件失败会使if语句短路并提前退出。

下面是一个例子:

if (condition a || condition b || condition c) {
 // This code will execute if condition a is true, condition a or b is true, or if all three are true
}
if (condition a && condition b && condition c) {
 // This code will only execute if all three are true, but if a is false, it will exit early, the same can be said for b
}