Is the if statement guaranteed not to be evaluated more than necessary?

Given two conditions with the && compound. I know that the evaluation order is from left to right. But if the first condition allows false, then the second condition is guaranteed not to be 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 should not be evaluated, since access in the array will be out of range.

By the way, I cannot just nest conditional expressions with two if , since in fact I need the opposite, like (!(in_range && get_element)) . With nested statements, I will need to use goto to jump over the code block below this.

+6
source share
1 answer

But if the first condition allows false, then the second condition is guaranteed not to be evaluated?

Yes, this is a short circuit in C ++. In clause 5.14 / 1 of the C ++ 11 standard:

The operators of the && group from left to right. The operands are converted to the context form in bool (section 4). The result is true if both operands are true and false otherwise. Unlike & , && guarantees a left-to-right evaluation: the second operand is not evaluated if the first operand is false .

Like MatthieuM. correctly mentioned in the comments , the above applies only to the built-in logical operators AND and logical OR: if these operators are overloaded, their call is considered as a normal function call (therefore, a short circuit is not applied and there is no guaranteed evaluation order).

As indicated in paragraph 5/2:

[Note. Operators can be overloaded, that is, values ​​are specified when applied to expressions of the type of a class (clause 9) or the type of an enumeration (7.2). Using overloaded statements translates into function calls, as described in 13.5. Overloaded operators obey the syntax rules specified in clause 5, but the requirements are the operand type, category of values, and evaluation order replaced by the rules for calling the function . [...] -end note]

+15
source

Source: https://habr.com/ru/post/945480/


All Articles