|
|
|
|
|
|
|
The For loop is easier to understand and is less prone to error. |
|
|
|
|
|
|
|
|
A good rule of thumb is: Use break within loops only as a last resort. Specifically, use it only to avoid baffling combinations of multiple Boolean flags and nested Ifs. |
|
|
|
|
|
|
|
|
Another statement that alters the flow of control in a C++ program is the continue statement. This statement, valid only in loops, terminates the current loop iteration (but not the entire loop). It causes an immediate branch to the bottom of the loopskipping the rest of the statements in the loop bodyin preparation for the next iteration. Here is an example of a reading loop in which we want to process only the positive numbers in an input file: |
|
|
|
|
|
|
|
|
for (dataCount = 1; dataCount <= 500; dataCount++)
{
dataFile >> inputVal;
if (inputVal <= 0)
continue;
cout << inputVal;
.
.
.
} |
|
|
|
|
|
|
|
|
If inputVal is less than or equal to 0, control branches to the bottom of the loop. Then, as with any For loop, the computer increments dataCount and performs the loop test before going on to the next iteration. |
|
|
|
|
|
|
|
|
The continue statement is not used often, but we present it for completeness (and because you may run across it in other people's programs). Its primary purpose is to avoid obscuring the main process of the loop by indenting it within an If statement. For example, the above code would be written without a continue statement as follows: |
|
|
|
|
|
|
|
|
for (dataCount = 1; dataCount <= 500; dataCount++)
{
dataFile >> inputVal;
if (inputVal > 0)
{
cout << inputVal;
.
.
.
}
} |
|
|
|
|
|
|
|
|
Be sure to note the difference between continue and break. The continue statement means Abandon the current iteration of the loop, and go on to the next iteration. The break statement means Exit the entire loop immediately. |
|
|
|
|
|