问题描述
是否可以保证逻辑运算符(&&
||
)的从左到右评估?
Is left-to-right evaluation of logical 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
和b
.与b
相比,要求a
失败的可能性更大.那么说if (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.
重要通知 :这对于内置&&
和||
仅有效;如果某些犯罪分子使它们重载,则将它们视为常规"重载二元运算符,因此在这种情况下,总是对和操作数进行评估,并且照常以未指定的顺序进行操作.因此,永远不要重载它们-这打破了关于程序控制流的极其重要的假设.
Important notice: this is valid only for the builtin &&
and ||
; if some criminal overloads them, they are treated as "regular" overloaded binary operators, so in this case both operands are always evaluated, and in unspecified order as usual. For this reason, never overload them - it breaks a hugely important assumption about the control flow of the program.
§5.14¶1
§5.15¶1
如果重载,它们将充当常规"二进制运算符(没有短路或保证评估的顺序)
§13.5¶9
If overloaded, they behave as "regular" binary operators (no short-circuit or guaranteed ordering of evaluation)
§13.5 ¶9
这些子节中未明确提及
,&&
和||
,因此常规的第13.5.2节认为:
and &&
and ||
are not mentioned explicitly in these subclauses, so regular §13.5.2 holds:
§13.5.2¶1
没有特殊规定,只能评估一方或以特定顺序进行评估.
with no special provision for evaluating only one side or in a particular order.
(所有引用均来自C ++ 11标准)
(all quotations from the C++11 standard)
这篇关于逻辑与,或:可以保证从左到右的评估吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!