The code I used is
int i=0, j=0; j=i++ + ++i;
And the output I got is i=2 and j=2
Could anyone explain how this happens!
The code I used is
int i=0, j=0; j=i++ + ++i;
And the output I got is i=2 and j=2
Could anyone explain how this happens!
i++
will "retrieve" 0 and then add 1 to i
. ++i
will add 1 to i
and then retrieve its value. Thus, this is equivalent to j = 0 + 2
. It also adds 1 to i
twice. Hence, i = 2
and j = 2
.
i++ increments the value of i and returns the previous value it held and ++i increments the value and returns the new value. So in your equation the i++ increments i by 1 and returns the previous value 0. And as i is already incremented by 1 so now value of i is 1. Then this i will be incremented in ++i and return value will be the new value 2. So 0+2 is the value of j in the equation.
The expression is evaluated in below steps:
Step 1 : j = i++ + ++i; => j = 0 + ++i; step result i = 1 and j = 0 (post increment will update the value but returns the old value)
Step 2 : j = 0 + ++i; => j = 0 + 2; step result i = 2 and j = 0 (pre increment will update the value and returns the updated value)
Step 3 : j = 0 + 2; => j = 2; step result i = 2 and j = 2 (direct addition and assign value to j)