Confusing output for if/else code

I am at a loss as to how the output for this code is equal to 2? I feel like the "++n < 3" part would cause the "if" statement to fail, as 3 < 3 is an incorrect statement. In addition, even if the "if" statement succeeded for some reason, it would increase n to 3, but then the "else" statement should be ignored. Can someone please explain to me why 2 is the output?

1
2
3
4
5
6
7
8
int n = 2;
if (n <= 2 && ++n < 3)
    n++;
else
    n--;
cout << n;
return 0;
}
First it will evaluate the expression n <= 2 and because it is true the expression ++n < 3 is also evaluated. Note that this expression changes the value of n so after this the value of n will be 3. In the else part of the if statement n is decremented so the value of n is once again equal to 2.
n is initialised as 2;
the ++n < 3 statement increased n to 3;
it fails the test;
statements in else is executed;
n-- reduced n to 2;
output 2;
Thanks for the information. I was unaware that a "++n" in an "if" statement would actually raise the value of the number.

So, if you wanted to do the same evaluation without changing the value of n at that part of the code, you would have to use "n+1" rather than "++n" right? I just want to make sure I understand that right and don't accidentally changes values of some variables in future code.
Yeah, that's right. If you don't want to change the value of n you should use n + 1.
Topic archived. No new replies allowed.