< previous page page_472 next page >

Page 472
The Break and Continue Statements
The break statement, which we introduced with the Switch statement, is also used with loops. A break statement causes an immediate exit from the innermost Switch, While, Do-While, or For statement in which it appears. Notice the word innermost. If break is in a loop that is nested inside another loop, control exits the inner loop but not the outer.
One of the more common ways of using break with loops is to set up an infinite loop and use If tests to exit the loop. Suppose we want to input 10 pairs of integers, performing data validation and computing the square root of the sum of each pair. For data validation, assume that the first number must be less than 100 and the second must be greater than 50. Also, after each input, we want to test the state of the stream for EOF. Here's a loop using break statements to accomplish the task (assume TRUE has been defined as the integer 1):
loopCount = 1;
while (TRUE)
{
    cin >> numl;
    if ( !cin || numl >= 100)
        break;
    cin >> num2;
    if ( !cin || num2 <= 50)
        break;
    cout << sqrt(float (numl + num2)) << endl;
    loopCount++;
    if (loopCount > 10)
        break;
}
Note that we could have used a For loop to count from 1 to 10, breaking out of it as necessary. However, this loop is both count-controlled and eventcontrolled, so we prefer to use a While loop.
The above loop contains three distinct exit points. Some people vigorously oppose this style of programming, as it violates the single-entry, singleexit philosophy we discussed with multiple returns from a function. Is there any advantage to using an infinite loop in conjunction with break? To answer this question, let's rewrite the loop without using break statements. The loop must terminate when numl is invalid or num2 is invalid or loopCount exceeds 10. We'll use Boolean flags to signal invalid data in the While condition:

 
< previous page page_472 next page >