Can You Spot the Infinite Loop?

Can you spot the infinite loop in the following snippet of code?

int i = 0;
{
    i++;
}while(i < 5);

The above code caused a critical bug in a application I was working on. At first sight, the code looks okay, especially since it compiles. It’s a do-while loop with a condition that seems that it would break when the variable i is equals or greater than 5. The variable i is set and incremented correctly but unfortunately this causes an infinite do nothing loop. Did you spot the problem? An important keyword is missing from the do-while loop, the do. Let me add comments to explain each statement as the compiler sees it…

// Initialize the variable i
int i = 0;

// Create a block and increment i by one
{
    i++;
}

// Infinite loop with an empty code block
while(i < 5);

The problem is that the while loop can have zero or one code block of statements (where a single statement can be a code block). If the state of what you are testing in the condition does not change because of the test, or because of the statement you are looping over, then you have an infinite loop. In the above code, because of a badly written do-while loop, this loop does not have statements that update the variables in the condition and so this while loop never breaks out.

The correct code would be the following…

int i = 0;
do {
    i++;
}while(i < 5);