|
|
|
|
|
|
|
In the preceding chapters, we introduced C++ statements for sequence, selection, loop, and subprogram. In some cases, we introduced more than one way of implementing these structures. For example, selection may be implemented by an If-Then statement or an If-Then-Else statement. The If-Then is sufficient to implement any selection structure, but C++ provides the If-Then-Else for convenience because the two-way branch is frequently used in programming. |
|
|
|
|
|
|
|
|
This chapter introduces five new statements that are also nonessential to, but nonetheless convenient for, programming. One, the Switch statement, makes it easier to write selection structures that have many branches. Two new looping statements, For and Do-While, make it easier to program certain types of loops. The other two statements, break and continue, are control statements that are used as part of larger looping and selection structures. |
|
|
|
|
|
|
|
|
The Switch statement is a selection control structure that allows us to list any number of branches. In other words, it is a control structure for multiway branches. A Switch is similar to nested If statements. The value of the switch expressionan expression whose value is matched with a label attached to a branchdetermines which one of the branches is executed. For example, look at the following statement: |
|
|
|
|
|
|
|
|
switch (letter)
{
case X : Statement1;
break;
case L :
case M : Statement2;
break;
case S : Statement3;
break;
default : Statement4;
}
Statement5; |
|
|
|
|
|
|
|
|
In this example, letter is the switch expression. The statement means If letter is X, execute Statement1 and break out of the Switch statement, continuing with Statement5. If letter is L or M, execute Statement2 and continue with Statement5. If letter is S, execute Statement3 and continue with Statement5. If letter is none of the characters mentioned, execute |
|
|
|
|
|