Re: Q about increment and assignment
jupiter wrote:
"John W. Kennedy" <jwkenne@attglobal.net> wrote in message
news:c0ijh.1967$Bf.27@newsfe12.lga...
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...
No, it gets expanded into:
t = i;
John, is t a copy of the bits in i made by the postfix ++ method?
The sample code is a Java equivalent to the original statement.
i = i + 1;
i = t;
Is it fair then to say that t gets restored because of the way the
postfix operator applies only after the expression is evaluated?
What is the difference between the original problem and this one?
int i=1;
System.out.println("i=" + i++); //output=1
System.out.println("i=" + i);//output=2
The new version does not assign the result of i++ to i, so the increment
side effect does not get overwritten by the value of i++.
I find this one easier to understand because eventually the new
bits do output. They don't get overwritten. In the original problem
there is overwriting going on that cause the 2 value to be lost
entirely. Is this due to the self-referencing aspect of the
original problem i=i++;?
It is not a self reference problem so much as an issue of multiple side
effects that act on the same data item. Generally, multiple side effects
in one statement make it harder to read and understand, and so should be
avoided. Code with multiple side effects on the same bits is a
particularly bad idea.
One last question: Where is that temp copy of the bits visible? I
can't see it in a debugger, so maybe I'm not using it (Eclipse) to
great advantage. I see the original i bits on the stack and that's
about it. This should not involve heap storage, so that leaves me
wondering where/how I'd ever see that temp set of bits.
The JVM can do it any way it likes, as long as it gets the proper
results and side effects. It is not required to make a temporary
variable anywhere that would be visible, as long as it ensures the
following:
1. Side effects happen in the proper order. Specifically, all side
effects of evaluating the right hand side of an assignment must happen
before the assignment.
2. The value of i++ is the old value of i.
Patricia