-1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Virat
  • 77
  • 7

2 Answers2

7

When you write x++, that means two things:

  • return current value
  • increment x

Since current value is 10 and 10 > 10 is false, the part after &&, including ++y, is not evaluated.

An alternative would be prefix increment, i.e., ++x.

lorro
  • 10,687
  • 23
  • 36
4

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335