OverIQ.com

The Infinite Loop in C

Last updated on July 27, 2020


A loop that repeats indefinitely and never terminates is called an Infinite loop.

Most of the time we create infinite loops by mistake. However, this doesn't mean that the infinite loops are not useful. Infinite loops are commonly used in programs that keep running for long periods of time until they are stopped like the web server.

In the following examples, we demonstrate what kind of mistakes can lead to an infinite loop:

Example 1:

1
2
3
4
5
6
short int i;

for (i = 32765; i < 32768; i++) 
{
    printf("%d\n", i);
}

This loop is an infinite loop. Here is why? According to the condition, the loop will execute until (i < 32768). Initially, the value of i is 32765 and after each iteration, its value is incremented by the update expression (i++). But the value of short int type ranges from -32768 to 32767. If you try to increment the value of i beyond 32767, it goes on the negative side and this process keeps repeating indefinitely. Hence the condition (i < 32768) will always be true.

Example 2:

1
2
3
4
5
6
int i = 1;

while(i<10)
{
    printf("%d\n", i); 
}

Here we are not updating the value of i. So after each iteration, the value of i remains the same. As a result, the condition (i<10) will always be true. For the loop to work correctly add i++;, just after the printf() statement.

Always remember, it is easy to forget update expression in while and do while loop, than in the for loop.

Example 3:

Another common mistake that leads to an infinite loop is to use the assignment operator (=) where the equality operator is needed (==).

1
2
3
4
5
6
int i = 1;

while(i=10)
{
    printf("%d", i);
}

What we actually wanted is that loop should execute until i is equal to 10. The value of the whole expression (i=10) is 10, since a non-zero value is considered true, the condition is always true and the loop will go on to execute indefinitely. To fix the problem replace the expression (i=10) with (i==10).

Example 4:

1
2
3
4
5
6
7
float f = 2;

while(f != 31.0)
{
    printf("%f\n", f);
    f += 0.1;
}

This loop is infinite because computers represent floating point numbers as approximate numbers, so 3.0 may be stored as 2.999999 or 3.00001. So the condition (f != 31.0) never becomes false. To fix this problem write the condition as f <= 31.0.

Example 5:

1
2
3
4
int i = 0;

while(i<=5);
printf("%d\n", i);

This loop will produce no output and will go on executing indefinitely. Take a closer look and notice the semicolon ( ; ) at the end of while condition. We know semicolon ( ; ) after the condition is a null statement. So the loop is equivalent to the following:

1
2
3
4
5
6
7
8
int i = 0;

while(i<=5)
{
    ; // a null statement
}

printf("%d\n", i);

We can now clearly see that we are not updating the value if i inside the while loop. As a result, it will go on executing indefinitely.