+ 4
++2 + 2++ gives output 7, how..?can anyone explain me about this result?
1 Resposta
+ 5
Basically there are two types of increments.
1) Pre-increment
In this case the increment operator comes before the variable.
Now in case of pre-increment, the variable is first incremented and then a value is returned.
eg: int a=2;
int x = ++a; // x=3 and a=3
2) Post-increment
In this case the increment operator comes after the variable.
Post-increment first returns the current value and then increments the number.
eg: int a=2;
int x = a++; // x=2 and a=3
But this is true only if the the increment is used in an expression containing an assignment.
But in this case since there is no assignment i.e. = involved, ++2 and 2++ will have the same effect.
So ++2 makes 3.
But since 2++ is written in the same statement after the ++2, the value passed to 2++ is 3 intead of 2.
Hence in this case 2++ gives 3+1 i.e. 4
Thus the expression ++2 + 2++ evaluates to
3+4 i.e 7.