C Language Iteration Statements/Loops: for, while, do-while Infinite Loops


Example

A loop is said to be an infinite loop if the control enters but never leaves the body of the loop. This happens when the test condition of the loop never evaluates to false.

Example:

C99
for (int i = 0; i >= 0; )
{
    /* body of the loop where i is not changed*/
}

In the above example, the variable i, the iterator, is initialized to 0. The test condition is initially true. However, i is not modified anywhere in the body and the update expression is empty. Hence, i will remain 0, and the test condition will never evaluate to false, leading to an infinite loop.

Assuming that there are no jump statements, another way an infinite loop might be formed is by explicitly keeping the condition true:

while (true)
{
    /* body of the loop */
}

In a for loop, the condition statement optional. In this case, the condition is always true vacuously, leading to an infinite loop.

for (;;)
{
    /* body of the loop */
}

However, in certain cases, the condition might be kept true intentionally, with the intention of exiting the loop using a jump statement such as break.

while (true)
{
    /* statements */
    if (condition)
    {
         /* more statements */
         break;
    }
}