问题
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])
{
// ...
}
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.
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.
回答1:
But if the first condition resolves to false, it the second condition guaranteed to not get evaluated?
Yes, that's C++'s short circuiting. Per paragraph 5.14/1 of the C++11 Standard:
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, 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).
As specified in paragraph 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://stackoverflow.com/questions/16666125/is-an-if-statement-guaranteed-to-not-be-evaluated-more-than-necessary