C++布尔值短路
我是 C++ 新手,很好奇编译器如何处理布尔值的惰性求值。例如,
if(A == 1 || B == 2){...}
如果 A 等于 1,则 B==2 部分是否已计算?
I'm new to c++ and am curious how the compiler handles lazy evaluation of booleans. For example,
if(A == 1 || B == 2){...}
If A does equal 1, is the B==2 part ever evaluated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
不,
B==2
部分不会被评估。这称为短路评估。编辑:正如Robert C. Cartaino正确指出的< /a>,如果逻辑运算符重载,则不会发生短路评估(话虽如此,为什么有人会重载逻辑运算符超出了我的范围)。
No, the
B==2
part is not evaluated. This is called short-circuit evaluation.Edit: As Robert C. Cartaino rightly points out, if the logical operator is overloaded, short-circuit evaluation does not take place (that having been said, why someone would overload a logical operator is beyond me).
除非
||
运算符重载,否则不会计算第二个表达式。这称为“短路评估”。在逻辑 AND (&&) 和逻辑 OR (||) 的情况下,如果第一个表达式足以确定整个表达式的值,则不会计算第二个表达式。
在上面描述的情况下:
...第二个表达式将不会被计算,因为
TRUE || ANYTHING
,始终评估为TRUE
。同样,
FALSE && ANYTHING
,始终评估为FALSE
,因此该情况也会导致一些简短说明
&&
和||
运算符。Unless the
||
operator is overloaded, the second expression will not be evaluated. This is called "short-circuit evaluation."In the case of logical AND (&&) and logical OR (||), the second expression will not be evaluated if the first expression is sufficient to determine the value of the entire expression.
In the case you described above:
...the second expression will not be evaluated because
TRUE || ANYTHING
, always evaluates toTRUE
.Likewise,
FALSE && ANYTHING
, always evaluates toFALSE
, so that condition will also cause a short-circuit evaluation.A couple of quick notes
&&
and||
operators.B==2 部分不被评估。
小心!不要把 ++B==2 之类的东西放在那里!
The B==2 part is not evaluated.
Be careful! Don't put something like ++B==2 over there!
C++ 将短路应用于布尔表达式求值,因此,
B == 2
永远不会被评估,编译器甚至可能完全忽略它。C++ applies short circuiting to Boolean expression evaluation so, the
B == 2
is never evaluated and the compiler may even omit it entirely.编译器通过生成中间跳转来处理这个问题。对于以下代码:
编译为伪汇编程序,可能是:
The compiler handles this by generating intermediate jumps. For the following code:
compiled to pseudo-assembler, might be:
正如 James 所说,这是短路评估。 惰性评估是完全不同的东西。
This is short-circuit evaluation, as James says. Lazy evaluation is something entirely different.
不,不是。
与
&&
相同,如果其中一个错误,则不会费心评估另一个。No it's not.
Same with
&&
, if one is wrong, it doesn't bother evaluating the other one.B == 2
永远不会被评估。有关详细信息,请参阅短路评估。
B == 2
is never evaluated.See Short-Circuit Evaluation for more information.