Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

If the first operand of the logical AND operator evaluates to false then the second operand is not evaluated because the velue 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading