< previous page page_125 next page >

Page 125
LISTING 8.12 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
20:               break;
21:        }
22:        return 0;
23:    }

Output:
How many hellos?  3
Hello!
Hello!
Hello!
Analysis: The for loop has now been pushed to its absolute limit. Initialization, test, and action have all been taken out of the for statement. The initialization is done on line 8, before the for loop begins. The test is done in a separate if statement on line 14, and if the test succeeds, the actionan increment to counteris performed on line 17. If the test fails, breaking out of the loop occurs on line 20.
Although this particular program is somewhat absurd, there are times when a for(;;) loop or a while(1) loop is just what you'll want. You'll see an example of a more reasonable use of such loops when switch statements are discussed.
Empty for Loops
So much can be done in the header of a for statement that there are times you won't need the body to do anything at all. In that case, be sure to put a null statement (;) as the body of the loop. The semicolon can be on the same line as the header, but this is easy to overlook. Listing 8.13 illustrates how this is done.
LISTING 8.13 ILLUSTRATING Anull STATEMENT IN Afor LOOP

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:     //Listing 8.13
2:     //Demonstrates null statement
3:     // as body of for loop
4:
5:     #include <iostream.h>
6:     int main()
7:     {
8:        for (int i = 0; i<5; cout < i:  < i++ < endl)
9:           ;
10:      return 0;
11:    }

Output:
i: 0
i: 1
i: 2
i: 3
i: 4

 
< previous page page_125 next page >

If you like this book, buy it!