8.3 switch, break, and continue

I l @ ve RuBoard

The break statement has two uses. Used inside a switch , it causes the program to exit the switch statement. Inside a for or while loop, it causes a loop exit. The continue statement is valid only inside a loop and causes the program to go to the top of the loop.

To illustrate how these statements work, we've produced a new version of the calculator program. The new program prints the result only after valid data is input, and it has a help command.

The help command is special. We don't want to print the result after the help command, so instead of ending the help case with a break , we end it with a continue . The continue forces execution to go to the top of the loop.

When an unknown operator is entered, we print an error message. As with the help case , we use a continue statement to skip printing the result.

Finally, there is one special command: quit. This command is handled outside the switch . It is handled by the break at the top of the loop. Since the break is outside the switch, it belongs to the while loop and causes the program to exit the while .

The control flow for this program can be seen in Figure 8-2.

Figure 8-2. switch/continue
figs/c++2_0802.gif
I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net