Sams Teach Yourself C++ in 21 Days

(singke) #1
More on Program Flow 191

7


Null Statements in forLoops
Any or all the statements in a forloop can be left out. To accomplish this, you use a null
statement. A null statement is simply the use of a semicolon (;) to mark where the state-
ment would have been. Using a null statement, you can create a forloop that acts
exactly like a whileloop by leaving out the first and third statements. Listing 7.11 illus-
trates this idea.

LISTING7.11 Null Statements in forLoops


1: // Listing 7.11
2: // For loops with null statements
3:
4: #include <iostream>
5:
6: int main()
7: {
8: int counter = 0;
9:
10: for( ; counter < 5; )
11: {
12: counter++;
13: std::cout << “Looping! “;
14: }
15:
16: std::cout << “\nCounter: “ << counter << std::endl;
17: return 0;
18: }

Looping! Looping! Looping! Looping! Looping!
Counter: 5.
You might recognize this as exactly like the whileloop illustrated in Listing 7.8.
On line 8, the countervariable is initialized. The forstatement on line 10 does
not initialize any values, but it does include a test for counter < 5. No increment state-
ment exists, so this loop behaves exactly as if it had been written:
while (counter < 5)
You can once again see that C++ gives you several ways to accomplish the same thing.
No experienced C++ programmer would use a forloop in this way shown in Listing
7.11, but it does illustrate the flexibility of the forstatement. In fact, it is possible, using
breakand continue, to create a forloop with none of the three statements. Listing 7.12
illustrates how.

OUTPUT


ANALYSIS
Free download pdf