adBrite

Your Ad Here

music

BidVertiser

Tuesday, September 21, 2010

Illustrating empty for loop statement.

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 7.12 illustrates how.
Listing 7.12. Illustrating empty for loop statement.
1: //Listing 7.12 illustrating
2: //empty for loop statement
3:
4: #include
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
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 action, an increment to counter, is performed on line 17. If the test fails, breaking out of the loop occurs on line 20.
While this particular program is somewhat absurd, there are times when a for(;;) loop or a while (1) loop is just what you'll want.

No comments:

Post a Comment

clicksor

Go Daddy Girl Ella Koon- $7.49 .COM Domains
CompUSA