Sunday 20 November 2011

What is the difference between a null loop and an infinite loop? in C programming

What is the difference between a null loop and an infinite loop?

A null loop does not continue indefinitely—it has a predefined number of iterations before exiting the loop. An infinite loop, on the other hand, continues without end and never exits the loop. This is best illustrated by comparing a null loop to an infinite loop.

Here is an example of a null loop:

for (x=0; x<500000; x++);

Notice that in this example, a semicolon is placed directly after the closing parenthesis of the for loop. As you might already know, C does not require semicolons to follow for loops. Usually, only the statements within the for loop are appended with semicolons. Putting the semicolon directly after the for loop (and using no braces) creates a null loop—literally, a loop that contains no programming statements. In the preceding example, when the for loop executes, the variable x will be incremented 500,000 times with no processing occurring between increments.

You might be wondering what null loops are used for. Most often, they are used for putting a pause in your program. The preceding example will make your program “pause” for however long it takes your computer to count to 500,000. However, there are many more uses for null loops. Consider the next example: while (!kbhit()); 

This example uses a null loop to wait for a key to be pressed on the keyboard. This can be useful when your program needs to display a message such as Press Any Key To Continue or something similar (let’s hope your users are smart enough to avoid an endless search for the “Any Key”!). An infinite loop, unlike a null loop, can never be terminated. Here is an example of an infinite loop:

while (1);

In this example, the while statement contains a constant that is nonzero. Therefore, the while condition will always evaluate to true and will never terminate. Notice that a semicolon is appended directly to the end of the closing parenthesis, and thus the while statement contains no other programming statements. Therefore, there is no way that this loop can terminate (unless, of course, the program is terminated).

Cross Reference:

XIX.15: What is the difference between continue and break?

3 comments: