是否保证if语句不会被超出必要的评估范围? [英] Is an if statement guaranteed to not be evaluated more than necessary?

查看:115
本文介绍了是否保证if语句不会被超出必要的评估范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用&&连接给出两个条件.我知道评估的顺序是从左到右.但是,如果第一个条件解析为假,那么第二个条件保证不会被评估吗?

Given two conditions with an && connection. I know that the order of evaluation is from left to right. But if the first condition resolves to false, it the second condition guaranteed to not get evaluated?

#define SIZE
bool array[SIZE];
int index;

// play with variables
// ...

if(index < SIZE && array[index])
{
    // ...
}

在此示例中,如果第一个条件为false,则第二个条件不得评估,因为数组中的访问将超出范围.

In this example, if the first condition is false the second must not be evaluated since the access in the array would be out of range.

顺便说一下,我不能简单地将条件语句嵌套在两个if语句中,因为实际上我需要像(!(in_range && get_element))这样的逆函数.对于嵌套语句,我需要使用goto跳过其下面的代码块.

By the way I cannot simply nest the conditionals with two if statements, since actually I need the inverse like (!(in_range && get_element)). With nested statements I would need to use goto to jump over the code block below that.

推荐答案

但是如果第一个条件解析为false,那么第二个条件保证不会被评估吗?

But if the first condition resolves to false, it the second condition guaranteed to not get evaluated?

是的,这是C ++的短路.根据C ++ 11标准的第5.14/1段:

Yes, that's C++'s short circuiting. Per paragraph 5.14/1 of the C++11 Standard:

&&运算符从左到右分组.操作数都在上下文中转换为bool(第4条). 如果两个操作数均为true,则结果为true,否则为false.与&不同,&&保证从左到右 评估:如果第一个操作数为false ,则不评估第二个操作数.

The && operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

按马修.在注释中正确提及,上面的内容仅适用于内置的逻辑AND和逻辑OR运算符:如果这些运算符已重载,则调用它们将被视为常规函数调用(因此不会发生短路,并且不会保证评估顺序.

As MatthieuM. correctly mentions in the comments, the above applies only to the built-in logical AND and logical OR operators: if those operators are overloaded, invoking them is treated as a regular function call (so no short-circuiting applies and no order of evaluation is guaranteed).

如第5/2段所述:

[注意:运算符可以重载,即,当应用于类类型的表达式时,它具有给定的含义(子句 9)或枚举类型(7.2). 重载运算符的使用已转换为函数调用,如所述 在13.5中.重载的运算符遵循第5章中指定的语法规则,但要求 操作数类型,值类别和评估顺序将替换为函数调用规则. [...] — 尾注]

[Note: Operators can be overloaded, that is, given meaning when applied to expressions of class type (Clause 9) or enumeration type (7.2). Uses of overloaded operators are transformed into function calls as described in 13.5. Overloaded operators obey the rules for syntax specified in Clause 5, but the requirements of operand type, value category, and evaluation order are replaced by the rules for function call. [...] —end note ]

这篇关于是否保证if语句不会被超出必要的评估范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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