I am not understanding why this post increment equation does not increase. I would have thought that after the += operation the value would increment by 1 and then the second time around i would have a 1 value. But the output is an infinite loop of 0 zero. Is anyone able to explain why 'i' doesn't increase.
int i = 0;
for(; ; ) {
if ( i >= 10) break;
i += i++;
}
System.out.println(i);
While the answer from @njzk2 is correct, it is useful to point out why it is correct.
There are other possibilities - for example, why doesn't Java execute the postincrement operator after the assignment? (Answer: because that's not what the Java Language Designers chose)
The evaluation order for compound assignments (things like
+=
) is specified in the Java Language Specification section 15.26.2. I'll quote how it is defined for Java 8:The most important thing is that the value of the left hand expression is saved first, then the right hand is completely evaluated, and then the result of the compound operation is stored in the variable on the left hand side.
Let's examine
i += i++;
i++
means read the value fori
, then incrementi
.i += x
means evaluatei
, then evaluatex
and add the 2 and put the result ini
.So, what happens is:
i
gets evaluated, it is0
i++
gets evaluated. it returns0
, and the value fori
is set to1
i += i++
is nowi = 0 + 0
.i = 0
Try with
++i
to get the result of the incrementation before reading its value.No surprise you are getting into infinity loop..
assume the above code, I have just replaced your line with increment with what compiler will substitute.
Now, initially i=0; So
results in i = 0 + 0 // and now i is 1
but at the end you again make i equal to 0!
Hence infinity...