> How does C++ handle &&? (Short-circuit evaluation) 7个
鉴于两个条件与&&连接.我知道评估的顺序是从左到右.但是如果第一个条件解析为false,那么第二个条件保证不会被评估?
#define SIZE bool array[SIZE]; int index; // play with variables // ... if(index < SIZE && array[index]) { // ... }@H_301_5@在此示例中,如果第一个条件为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 tobool
(Clause 4).
The result istrue
if both operands aretrue
andfalse
otherwise. Unlike&
,&&
guarantees left-to-right
evaluation: the second operand is not evaluated if the first operand isfalse
.
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 ]