+ 2
Doubt in increment operator
If x is already incremented in the if statement, then why does cout<<x give result 1 in the output (ideally the value of x in the memory has become 3 so 33 should be the answer) Can someone tell me where I am going wrong? Check out this code: https://code.sololearn.com/cF1V1QRl4qmU/?ref=app
2 Réponses
+ 3
This is a nice example of variable shadowing.
https://en.wikipedia.org/wiki/Variable_shadowing
By doing int x = 2 inside the if statement you are 'hiding' the x previously declared outside the if statement.
If we replace the second x by another name, it's easier to understand:
if (x>0)
{
int notX=2;
cout<<++notX;
}
This is basically what you are doing here.
Fix: Replace int x = 2; with x = 2;
+ 2
They are two different variables. The first x's value stays 1 and is never touched.