Search code examples
c++if-statementpost-incrementlogical-and

Why isn't the ++y part executing?


So here is the question I am given , I need to tell the output :

#include <iostream>
using namespace std;
int main()
{
    int x = 10;
    int y = 20;
    if(x++ > 10 && ++y > 20 ){
    cout << "Inside if ";
    } else{
    cout << "Inside else ";
    }
    cout << x << “ “ << y;
}

The ans given is Inside else 11 20 I checked with complier this is the correct answer but according to me the answer should be Inside else 11 21.

Why is this happening ? Why isn't the ++y part executing ?

I also tried y++ I still get same answer.


Solution

  • 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.