C++ IF语句是否检查每个OR运算符?
目前我正在用粒子进行测试,有一个重要的问题C++ IF语句是否检查每个OR运算符?,c++,performance,if-statement,C++,Performance,If Statement,目前我正在用粒子进行测试,有一个重要的问题 if (condition a || condition b || condition c) 或 哪个更快?C++使用所谓的短路表达式求值,这意味着一旦遇到决定表达式最终结果的术语,无论其余术语的求值结果如何,它都将停止求值 由于true或x为真,无论x的值如何,C++将不会麻烦地评估x.< 但是,级联if语句与第一个表达式不等价。它等价于一个多个不等于多个OR的表达式。< P>这可能是以前在其他地方回答过的,但是C++使用短路方法,即如果任何条件通
if (condition a || condition b || condition c)
或
哪个更快?C++使用所谓的短路表达式求值,这意味着一旦遇到决定表达式最终结果的术语,无论其余术语的求值结果如何,它都将停止求值
由于true或x为真,无论x的值如何,C++将不会麻烦地评估x.<
但是,级联if语句与第一个表达式不等价。它等价于一个多个不等于多个OR的表达式。< P>这可能是以前在其他地方回答过的,但是C++使用短路方法,即如果任何条件通过,其余的在逻辑或:< < /P>的情况下被忽略。 逻辑and的情况正好相反:&-第一个失败的条件会使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
}
这两者并不等同。所以你不能说,哪一个更快。但是,当您从条件开始时,第一个条件非常快,这很可能是真的,因为随后的条件将不会执行。对于&&则相反。那么第一个应该是最有可能是错误的
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
}