Playing with an Infinite Loop
If you have a for statement like this,
for ( ; ; ){
/* statement block */
}
you encounter an infinite loop. Note that in this for statement, there are no expressions in the three expression fields. The statements inside the statement block will be executed over and over without stopping.
You use the infinite loop if you don't know the exact number of loops you need. However, you have to set up some other conditions with the loop to test and determine whether and when you want to break the infinite loop.
The program in Listing 7.4 demonstrates an example that takes the characters entered by the user, and puts them on the screen. The for loop in the program keeps looping until the user enters the character x.
TYPE
Listing 7.4. Adding conditions to a for loop.
1: /* 07L04.c: Conditional loop */
2: #include <stdio.h>
3:
4: main()
5: {
6: int c;
7:
8: printf("Enter a character:\n(enter x to exit)\n");
9: for ( c=' `; c != `x'; ) {
10: c = getc(stdin);
11: putchar(c);
12: }
13: printf("\nOut of the for loop. Bye!\n");
14: return 0;
15: }
OUTPUT
After running the executable, 07L04.exe, I enter characters, such as H, i, and the \n character (I have to press the Enter key each time after I enter a character), which are all displayed back on the screen. Finally, I enter x to exit from the infinite for loop. (Note that in the following copy from the screen, the characters that I entered are in bold.)
C:\app> 07L04
Enter a character:
(enter x to exit)
H
H
i
i
x
x
Out of the for loop. Bye!
C:\app>
ANALYSIS
In Listing 7.4, there is only one integer variable, c, declared in line 6. The printf() function in line 8 displays the message Enter a character: on one line on the screen, and another message, (enter x to exit), on another line because there is a newline character (\n) added in the middle of the format string in the printf() function.
In line 9, the integer variable c is initialized with the numeric value of the space character. Then, a condition is evaluated in the second expression field of the for statement like this: c != `x', which means that the condition is met if c does not contain the numeric value of x; otherwise, the condition is not met.
If the condition is met, the two statements in lines 10 and 11 will be executed over and over. The looping can last forever until the user enters the character x. Then, the statement in line 13 prints out a good-bye message right after the looping is terminated.
- 7 views