逻辑比较:从左到右的评估是否保证? [英] Logical comparisons: Is left-to-right evaluation guaranteed?
问题描述
是否保证逻辑比较运算符(&&
||
)的从左到右评估?
Is left-to-right evaluation of logical comparison operators (&&
||
) guaranteed?
假设我有这个:
SDL_Event event;
if (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
// do stuff
}
}
这是否保证与此相同?
SDL_Event event;
if (SDL_PollEvent(&event) && event.type == SDL_QUIT) {
// do stuff
}
这也很重要,假设我们有两个要求: a
code> b 。需求 a
更有可能失败,然后 b
。然后,如果(a& b)比 if(b& a)
This can also be very important, let's say we have two requirements, a
and b
. Requirement a
is much more likely to fail then b
. Then it's more efficient to say if (a && b)
than if (b && a)
.
推荐答案
是的,这是保证的,否则这样的操作员会失去很多用处。
Yes, it's guaranteed, otherwise such operators would lose much of their usefulness.
相关标准报价:
§5.14¶1
与
&
,&&&
右对照评估:如果第一个操作数false
,则不评估第二个操作数。
Unlike
&
,&&
guarantees left-to-right evaluation: the second operand is not evaluated if the first operand isfalse
.
§5.15¶1
不同于
|
,||
保证从左到右的评估;此外,如果第一操作数计算true
,则不评估第二操作数。
Unlike
|
,||
guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates totrue
.
这篇关于逻辑比较:从左到右的评估是否保证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!