Analysis: You might recognize this as exactly like the while loop illustrated previously. On line 8, the counter variable is initialized. The for statement on line 10 does not initialize any values, but it does include a test for counter < 5. There is no increment statement, so this loop behaves exactly as if it had been written like this:
while (counter < 5)
Once again, C++ gives you a number of ways to accomplish the same thing. No experienced C++ programmer would use a for loop in this way, but it does illustrate the flexibility of the for statement. In fact, it is possible, using break and continue, to create a for loop with none of the three statements. Listing 8.12 illustrates how.
LISTING 8.12 ILLUSTRATING AN EMPTYfor LOOP STATEMENT
1: //Listing 8.12 illustrating
2: //empty for loop statement 3:
4: #include <iostream.h>
5:
6: int main()
7: {
8: int counter=0; // initialization
9: int max;
10: cout < How many hellos?;
11: cin >> max;
12: for (;;) // a for loop that doesn't end
13: {
14: if (counter < max) // test
15: {
16: cout < Hello!\n;
17: counter++; // increment
18: }
19: else