Breaking Out of an Infinite Loop in Your C Language Program

When you get into programming loops in the C language, you discover the joys and dreads of endless, or infinite, loops. These loops continue forever because either the programmer forgot to include a way to exit from the loop or the exit condition is just never met. Either way, endless loops are a pain.


But sometimes a C program contains an endless loop on purpose. This type of construct may seem odd, yet the basis of many modern programs is that they sit and spin while they wait for something to happen. The loop may look like this:


for(;;)
{
check_Keyboard();
check_Mouse();
check_Events();
check_System();
}

Notice that the conditions inside the parentheses after the for keyword are missing, which is okay. The result is an endless loop in which the statements are checked repeatedly, one after the other: The program is looking for activity somewhere. When activity is found, the program goes off and does something interesting. But most of the time, the program just sits in this type of loop, waiting for something to happen. (The typical word processor may perform thousands of these loops as it waits between keystrokes as you're typing.)


Enter this source code and save it to disk. Then compile and run the program:


#include <stdio.h>
int main()
{
char ch;
puts("Typing Program");
puts("Type away:");
for(;;)
{
ch=getchar();
}
return(0);
}

Yes, you can type. And you can see your text on the screen. But how do you stop?


To stop, you have to break the endless loop, which can be done by pressing Ctrl+C. But that isn't the way you want your programs to work. Instead, an exit condition must be defined for the loop, which is where the break keyword comes into play.


The C language developers knew that, in some instances, a loop must be broken based on conditions that could not be predicted or set up inside the for statement. So, in their wisdom, they introduced the break keyword.


What break does is to immediately quit a loop (any C language loop, not just for loops). When the computer sees break, it just assumes that the loop is done and continues as though the loop's ending condition was met:


#include <stdio.h>
int main()
{
char ch;
puts("Typing Program");
puts("Type away; press '~' to quit:");
for(;;)
{
ch=getchar();
if(ch=='~')
{
break;
}
}
return(0);
}

Now an exit condition is defined. The if comparison in Line 12 checks to see whether a ~ (tilde) character is entered. If so, the loop is halted by the break statement.


Change your source code so that it matches what was just shown. Compile and run. Now, you can halt the program by typing the ~ character.


Note that the if statement can also be written without the braces:


if(ch=='~') break;

This line may be a bit more readable than using braces.











dummies

Source:http://www.dummies.com/how-to/content/breaking-out-of-an-infinite-loop-in-your-c-languag.html

No comments:

Post a Comment