Search code examples
c++loopsif-statementinfinite-loop

Infinite for loop if condition


Code Snippet 1:

int i=1;
for(;;){
    if (i<5){
        cout<<"Hello World"<<endl;
        i++;
    }
}

Code Snippet 2:

int i=1;
for(;;){
    if (i<5){
        cout<<"Hello World"<<endl;
    }
    i++;
}

Snippet 1 produces an output where "Hello World" is printed 4 times and then the loop continues with no output, which was expected. But, "Hello World" is printed indefinitely in snippet 2. Why does the condition (i<5) not checked in snippet 2 even after i=>5? How does incrementing i (i++) inside or outside the if-block in these snippets making such a difference?


Solution

  • In the first snippet, when i reaches the value 5, it is no longer changed and keeps that value.

    In the second one, i keeps being increased. It will overflow, and that is enough to invoke Undefined Behaviour. Common implementations use 2-complement for negative numbers, so INT_MAX + 1 gives... a negative number (INT_MIN). Which is indeed smaller than 5!