In our context:
Pre means the increment or decrement is done before the statement is executed.
Post means the increment or decrement is done after the statement is executed.
So,
i = ++i + i++ + i-- + ++i;
(a) (b) (c) (d)
is equivalent to the following set of statements:
i = i+1; (a)
i = i +1; (d)
i = i + i + i + i; (the statement)
i = i + 1; (b)
i = i -1; (c)
Case 1:
So if initially the value of i was i = 10, then the value of i after the statement is executed will be:
i = 10 + 1;
i = 11 + 1;
i = 12 + 12 + 12 + 12;
i = 48 + 1;
i = 49-1;
Therefore if you use printf("%d", i) after the statement you will get 48 as the answer.
Case 2:
Now consider the case:
j = ++i + i++ + i-- + ++i;
printf("%d", j);
Then these statements are equivalent to:
i = i+1;
i = i +1;
j = i + i + i + i; (the statement)
i = i + 1;
i = i -1;
printf("%d", j);
Therefore if i is 10 initially,
i = 10 + 1;
i = 11 + 1;
j = 12 + 12 + 12 + 12;
i = 12 + 1;
i = 13 - 1;
printf("%d", j); will give j = 48. The final value of i in this case is 12.
PS: This logic holds for C and C++. It may differ in Java.
No comments:
Post a Comment