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.
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)
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_
So, in this
ifstatement:the left operand of the logical AND operator
x++ > 10evaluates tofalse. However, the side effect of the post-increment operator is applied to the variablex. The second operand++y > 20is not evaluated.So, the control will be passed to the
elsestatement, and within its sub-statementxwill be equal to11andywill keep its original value20.