逻辑与,或:可以保证从左到右的评估吗? [英] Logical AND, OR: Is left-to-right evaluation guaranteed?

查看:92
本文介绍了逻辑与,或:可以保证从左到右的评估吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以保证逻辑运算符(&& ||)的从左到右评估?

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
}

这也可能非常重要,假设我们有两个要求,ab.与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

&不同,&&保证从左到右求值:如果第一个操作数为false,则不对第二个操作数求值.

Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

§5.15¶1

|不同,||保证从左到右的评估;此外,如果第一个操作数的值为true,则不计算第二个操作数.

Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.

如果重载,它们将充当常规"二进制运算符(没有短路或保证评估的顺序)

§13.5¶9

If overloaded, they behave as "regular" binary operators (no short-circuit or guaranteed ordering of evaluation)

§13.5 ¶9

在13.5.3至13.5.7节中未明确提及的运算符充当服从13.5.1或13.5.2规则的普通一元和二进制运算符.

Operators not mentioned explicitly in subclauses 13.5.3 through 13.5.7 act as ordinary unary and binary operators obeying the rules of 13.5.1 or 13.5.2.

这些子节中未明确提及

&&||,因此常规的第13.5.2节认为:

and && and || are not mentioned explicitly in these subclauses, so regular §13.5.2 holds:

§13.5.2¶1

二进制运算符应通过具有一个参数的非静态成员函数(9.3)或具有两个参数的非成员函数来实现.因此,对于任何二进制运算符@,都可以解释x@y x.operator@(y)operator@(x,y).

A binary operator shall be implemented either by a non-static member function (9.3) with one parameter or by a non-member function with two parameters. Thus, for any binary operator @, x@y can be interpreted as either x.operator@(y) or operator@(x,y).

没有特殊规定,只能评估一方或以特定顺序进行评估.

with no special provision for evaluating only one side or in a particular order.

(所有引用均来自C ++ 11标准)

(all quotations from the C++11 standard)

这篇关于逻辑与,或:可以保证从左到右的评估吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆