+ 2

How this results in infinite loop i = i++?

for(int i=0 ; i<5;){ System.out.println(i); i = i++; }

6th Jun 2019, 2:31 PM
Heisenberg
Heisenberg - avatar
2 Respuestas
+ 3
i++ creates a copy of the old i, changes i and then returns the copy of the old i. So you create a copy, change the value, and then, using i = ... , store the old value again in i, effectively nullifying the change. Instead you should normally just write i++.
6th Jun 2019, 2:37 PM
HonFu
HonFu - avatar
+ 4
i = i++ means i equals i THEN increase i by one, so as HonFu said you're just re-storing the old value of i - it always equals 0, using just i++ is neater. You could also change it to i = ++i you change the order of actions to increase i by one THEN store the new value as i, and you'll get the result you want.
6th Jun 2019, 2:43 PM
Rincewind
Rincewind - avatar