Control Statements
Control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. (see Chapter 2 for a discussion of automatic and other object lifetimes)
C++ supports the following control statements:
break;A
breakstatement can be used only in the body of a loop orswitchstatement. It terminates the loop orswitchstatement and transfers execution to the statement immediately following the loop orswitch.In a nested loop or switch, the
breakapplies only to the innermost statement. To break out of multiple loops and switches, you must use agotostatement or redesign the block to avoid nested loops and switches (by factoring the inner statement into a separate function, for example). Example 4-7 shows a simple use ofbreak.Example 4-7. Using break to exit a loop// One way to implement the find_if standard algorithm. template<typename InIter, typename Predicate> InIter find_if(InIter first, InIter last, Predicate pred) { for ( ; first != last; ++first) if (pred(*first))break;return first; }continue;A
continuestatement can be used only in the body of a loop. It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating (if the condition istrue). In aforloop, theiterate-expris evaluated before testing the condition. Example 4-8 shows howcontinueis used in a loop.Example 4-8. Using continue in a loop#include <cmath> #include ...