I am running this infinite for
loop. Why is this for
loop terminating after some time?
for(int i = 10; i > 0; i++) { }
But if I print something in this for
loop then it is not terminating. Why so?
The int
wraps around to -2,147,483,648 when it reaches 2,147,483,647.
That causes the conditional i > 0
to evaluate to false
.
This is perfectly well-defined behaviour in Java: you can't do this though in C or C++.
If you are trying to print something in the loop, then the speed of the loop decreases substantially, and you're probably running out of patience. Incorporate the current value of i
in your output, and see for yourself: even 1,000 iterations of output per second would take nearly a month to reach the wrap-around point!
Arithmetic integer operations are performed in 32-bit precision. When the resultant value of an operation is larger than 32 bits (the maximum size an int variable can hold) then the low 32 bits only taken into consideration and the high order bits are discarded. When the MSB (most significant bit) is 1 then the value is treated as negative. In your case when it becomes negative and condition become false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With