Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this infinite for loop terminating after some time? [duplicate]

Tags:

java

for-loop

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?

like image 577
Ankit Avatar asked Dec 07 '22 18:12

Ankit


2 Answers

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!

like image 51
Bathsheba Avatar answered Apr 05 '23 23:04

Bathsheba


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.

like image 24
gati sahu Avatar answered Apr 05 '23 23:04

gati sahu