11

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.

danijar
  • 32,406
  • 45
  • 166
  • 297
  • 2
    This has pretty much nothing to do with the if statement. The if statement is executed only once too, but what you are asking about is in fact the behavior of the `&&` **operator**. –  May 21 '13 at 09:09
  • Feel free to edit tags and question title if it would better match the actual question. – danijar May 21 '13 at 09:11
  • Although the most exact duplicate is the one above, the answers are better here: http://stackoverflow.com/questions/5683026/logical-comparisons-is-left-to-right-evaluation-guaranteed, as well as here: http://stackoverflow.com/questions/628526/is-short-circuiting-boolean-operators-mandated-in-c-c-and-evaluation-order – jogojapan May 21 '13 at 09:22

1 Answers1

18

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 ]

Community
  • 1
  • 1
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451