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 ]

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...