Big D wrote:
> I'm confused by the output of the following code:
>
> public class PP {
> public static void main(String[] args) {
> int i = 1;
> i = i++;
> System.out.println(i);
> }
> }
>
> It outputs 1.
>
> I understand the assignment operator happening before the ++, but I don't
> understand why the ++ doesn't increment. I thought the statement should
> basically expand to:
>
> i = i;
> i = i+1;
>
> but the ++ gets lots somewhere...
>
In Java, any side effects of operand evaluation happen before side
effects of the operation that uses the operands. i++ will be completely
evaluated before the assignment of its value to i.
The value of "i++" is, by definition, the value of i prior to the
increment, so the assignment restores the old value of i. The code is
equivalent to:
int temp = i; // record the value of i++, the old value of i
i = i+1; // increment i
i = temp; // assign the value of i++ to i.
Patricia
|