c – if语句是否保证不被评估超过必要的?

前端之家收集整理的这篇文章主要介绍了c – if语句是否保证不被评估超过必要的?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Is short-circuiting logical operators mandated? And evaluation order?7个
> How does C++ handle &&? (Short-circuit evaluation) 7个
鉴于两个条件与&&连接.我知道评估的顺序是从左到右.但是如果第一个条件解析为false,那么第二个条件保证不会被评估?
#define SIZE
bool array[SIZE];
int index;

// play with variables
// ...

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

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

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

解决方法

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

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

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.

As MatthieuM. correctly mentions in the comments,以上仅适用于内置逻辑AND和逻辑OR运算符:如果这些运算符过载,则调用它们将被视为常规函数调用(因此不应用短路并且不保证评估顺序).

如第5/2段所述:

[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 ]

原文链接:https://www.f2er.com/c/116965.html

猜你在找的C&C++相关文章