< previous page page_471 next page >

Page 471
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
while (1)
    cout << H << endl;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Both of these are infinite loops that print Hi endlessly.
3. The initializing statement, InitStatement, can be a declaration with initialization:
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
for (int i = 1; i <= 20; i++)
    cout << Hi << endl;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
But you have to be careful here. The variable i is not local to the body of the loop. Its scope extends to the end of the block surrounding the For statement. In other words, it's as if i had been declared outside the loop. The following sequence of statements, therefore, produces a compiletime error:
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
for (int i = 1; i <= 20; i++)
    cout << Hi << endl;
for (int i = 1; i <= 100; i++) // Error--i already defined
    cout << Ed << endl;
As you have seen by now, the For statement in C++ is a very flexible structure. Its use can range from a simple count-controlled loop to a generalpurpose, anything goes While loop. Some programmers find it an intellectual challenge to see how much they can squeeze into the heading (the first line) of a For statement. For example, the program fragment
cin >> ch;
while (ch != .)
    cin >> ch;
can be compressed into the following For loop:
for (cin >> ch; ch != .; cin >> ch)
    ;
Because all the work is done in the For heading, there is nothing for the loop body to do. The body is simply the null statement.
With For statements, our advice is to keep things simple. The trickier the code is, the harder it will be for another person (or you!) to understand your code and track down errors. In this book, we use For loops for countcontrolled loops only.

 
< previous page page_471 next page >