c++ - Is an if statement guaranteed to not be evaluated more than necessary? -
this question has answer here:
given 2 conditions &&
connection. know order of evaluation left right. if first condition resolves false, second condition guaranteed not evaluated?
#define size bool array[size]; int index; // play variables // ... if(index < size && array[index]) { // ... }
in example, if first condition false second must not evaluated since access in array out of range.
by way cannot nest conditionals 2 if
statements, since need inverse (!(in_range && get_element))
. nested statements need use goto
jump on code block below that.
but if first condition resolves false, second condition guaranteed not evaluated?
yes, that's c++'s short circuiting. per paragraph 5.14/1 of c++11 standard:
the
&&
operator groups left-to-right. operands both contextually convertedbool
(clause 4). resulttrue
if both operandstrue
,false
otherwise. unlike&
,&&
guarantees left-to-right evaluation: the second operand not evaluated if first operandfalse
.
as matthieum. correctly mentions in comments, above applies built-in logical , and logical or operators: if operators overloaded, invoking them treated regular function call (so no short-circuiting applies , no order of evaluation guaranteed).
as specified in paragraph 5/2:
[note: operators can overloaded, is, given meaning when applied expressions of class type (clause 9) or enumeration type (7.2). uses of overloaded operators transformed function calls described in 13.5. overloaded operators obey rules syntax specified in clause 5, requirements of operand type, value category, , evaluation order replaced rules function call. [...] —end note ]
Comments
Post a Comment