I’ll show you a code C#:
using static System.Console;
public class Program {
public static void Main() {
for (int i = 1; i >= 0; i *= 2) { WriteLine($"i: {i}"); }
checked {
for (int j = 1; j >= 0; j *= 2) { WriteLine($"j: {j}"); }
}
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
I do not do with Java because it cannot control the check of overflow.
By default it is turned off, so when you arrive at a value above capacity that type int
supports it continues operating normally only that there is a signal exchange which is a bit in number. For the sake of performance it is not verified if this occurs. Being negative the loop closes.
The second I did turns on the check, it gets slower because every change of the variable has to see if it didn’t burst, but then an error happens because the processor indicates that the operation is invalid and the . NET captures this and information the execution.
But it can see in Java as well. I switched to multiply by 2 to go into geometric progression and close faster. I could also have started with a higher number.
The maximum size of int
is 2,147,483,647 (2 to 31 since it has 32 bits and one of them is used as a signal). The minimum value is -2,147,483,648.
So get into loop infinite:
class Loop {
public static void main(String[] a) {
int cont = 0;
for (int i = 1; i < 10000000000000000L; i *= 2, cont++) { System.out.println("i:" + i); }
System.out.println("cont:"+cont);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Because there comes a time when the
int
basically. When his counter crosses the line, he goes back to "the other side". Think of a car odometer, when the mileage goes past the one that fits it, it goes back to the beginning (which in the case of the int starts at -value and goes up to +value)– Bacco
@Bacco Claroo! 2.147.483.647 maximum value, as seen here, but knows some bibliography that cite this overflow in repetition structure?
– Luiz Augusto
The structure is irrelevant to the problem, until pq normally does not use it like this (has exercise face, someone took advantage of this "side effect" and created a scenario to show - rare situations could take real benefit from it) - Usually you have to know these limits to avoid bugs, not to explore.
– Bacco