If the first operand of the logical AND (&&
) operator evaluates to false, the second operand is not evaluated, because the value of the expression is already known.
From the C++ 20 Standard (7.6.14 Logical AND operator)
1 The && operator groups left-to-right. The operands are both contextually converted to bool (7.3). 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.
Also, the value of an expression with the post-increment operator is the value of its operand before incrementing.
From the C++ 20 Standard (7.6.1.6 Increment and decrement_
1 The value of a postfix ++ expression is the value of its operand...
So, in this if
statement:
if(x++ > 10 && ++y > 20 ){
the left operand of the logical AND operator x++ > 10
evaluates to false
. However, the side effect of the post-increment operator is applied to the variable x
. The second operand ++y > 20
is not evaluated.
So, the control will be passed to the else
statement, and within its sub-statement x
will be equal to 11
and y
will keep its original value 20
.