c++ - Is an if statement guaranteed to not be evaluated more than necessary? -


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 converted bool (clause 4). result true if both operands true , false otherwise. unlike &, && guarantees left-to-right evaluation: the second operand not evaluated if first operand false.

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

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -