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? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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); } }

26th Aug 2018, 3:29 AM
Mohammad Nadeem
Mohammad Nadeem - avatar
2 Answers
+ 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.
26th Aug 2018, 4:03 AM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 1
Thanks, Kinshuk
26th Aug 2018, 4:05 AM
Mohammad Nadeem
Mohammad Nadeem - avatar