Why is this loop "for" not infinite?

8
public class Loop {
public static void main(String[] a) {
int cont=0;
for (int i=0; i>=0; i+=2, cont++);
System.out.println("cont:"+cont); }}

I was struck by the condition of the loop for i>=0 . At the time I thought: loop infinite, but the code compiled and printed on the screen the value cont : 1073741824

Why does the for loop of that code not be infinite?

The value of the cont variable is due to the increment of course, but how many iterations did the loop for do to assign that value to the variable cont ?

Note: The code was exactly like this, without indentation.

    
asked by anonymous 31.08.2018 / 21:04

2 answers

8

I'll show you a C # code:

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}"); }
        }
    }
}

See running on .NET Fiddle . And in Coding Ground . Also put it in GitHub for future reference .

I do not do with Java because it can not control the overflow check.

By default it is turned off, so when you arrive at a value above the capacity that the int type supports it continues to operate normally only that there is a signal exchange that is a bit in the number. As a matter of performance it is not checked if this occurs. Being negative, the loop terminates.

The second I did bind the check, slows down because every change of the variable has to see if it did not break, but then an error ends up occurring because the processor indicates that the operation is invalid and .NET captures it and information the implementation.

But you can see Java too . I changed to multiply by 2 to get into geometric progression and quit more quickly. It could also have started with a larger number.

The maximum size of int is 2,147,483,647 (2 raised 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 it goes into loop infinity:

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);
    }
}

See working on ideone .

    
31.08.2018 / 21:19
-1

The int type has a maximum limit. Upon reaching this limit, the loop is terminated.

int = 4 bytes - 32 bits = -2147483648 a + 2147483647 - números inteiros

    
04.09.2018 / 19:39