Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an if statement guaranteed to not be evaluated more than necessary? [duplicate]

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.

like image 817
danijar Avatar asked May 21 '13 09:05

danijar


1 Answers

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 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, 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 ]

like image 186
Andy Prowl Avatar answered Sep 24 '22 05:09

Andy Prowl