+ 1
Why is the answer to this program 2 and not 3? The x++ doesn't cause the value of x to increase in the end? Why?
public class Program { public static void main(String[] args) { int x = 1; while( x < 2 ) { x += x++; } System.out.println(x); } }
2 Réponses
+ 4
Usually, modifying a variable twice in a single expression leads to undefined behaviour.
So the reason for the output is unpredicatble, as we don't know if x++ was evaluated before x+=x or if it was the other way round, as these expressions are evaluated at runtime.
If you ignore x++, x+=x may give you 2. Now, if the postfix part is evaluated before, and when you attempt to change the variable again, this modified value is lost. This however, may not be the case on some other system, and so the output is undefined.
+ 1
Thanks, Kinshuk