微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/c/116965.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐