ProAnswers.org

Why this Program goes in infinite loop?

One of my student wrote the following code:

public class Tests {
public static void main(String[] args) throws Exception {
int x = 0;
while(x<3) {
x = x++;
System.out.println(x); } } }

we know he should have writen just x++ or x=x+1, but on x = x++;
it should first attribute x to itself, and later increment x. Why does x continue with 0 as value?

Perhaps if we write out a method to do the equivalent of what x++ does it will make this clearer.

			public static int PostIncrement(ref int x) 
			{ 
			    int valueBeforeIncrement = x; 
			    x = valueBeforeIncrement + 1; 
			    return valueBeforeIncrement; 
			} 
			 
	



Right? Increment the value passed and return the original value: that's the definition of the postincrement operator.



Now, let's see how this behavior plays out in your example code:




	
		
			int x = 0; 
			x = PostIncrement(ref x); 
			 
	



PostIncrement(ref x) does what? Increments x, yes. And then [b]returns what x was before the increment[/b]. This return value then gets assigned to x.



So the order of values assigned to x is 0, then 1, then 0.



This might be clearer still if we re-write the above:

int x = 0; // x is 0.
int temp = PostIncrement(ref x); // Now x is 1, and temp is 0.
x = temp; // Now x is 0 again.

Your fixation on the fact that when you replace x on the left side of the above assignment with y, "you can see that it first increments x, and later attributes it to y" strikes me as confused. It is not x that is being assigned to y; it is [b]the value formerly assigned to x[/b]. Really, injecting y makes things no different from the scenario above; we've simply got:

int x = 0; // x is 0.
int y = 0; // y is 0.
int temp = PostIncrement(ref x); // Now x is 1, and temp is 0.
y = temp; // y is still 0.

So it's clear: x = x++ effectively does not change the value of x. It always causes x to have the values x0, then x0 + 1, and then x0 again.