Similar to the if statements, switch...case controls the flow
of programs by allowing the programmers to specify different codes that
should be executed in various conditions. In particular, a switch statement compares the value of a variable to the values specified in the case statements. When a case statement is found whose value matches that of the variable, the code in that case statement is run.
The break keyword makes the switch statement exit, and is typically used at the end of each case. Without a break statement, the switch statement will continue executing the following expressions ("falling-through") until a break, or the end of the switch statement is reached.
The break keyword makes the switch statement exit, and is typically used at the end of each case. Without a break statement, the switch statement will continue executing the following expressions ("falling-through") until a break, or the end of the switch statement is reached.
Switch Case Statement Syntax
switch (variable) { case label: // statements break; } case label: { // statements break; } default: { // statements break; }
Switch Case Statement Execution Sequence
Example
Here is a simple example with switch. Suppose we have a variable phase with only 3 different states (0, 1, or 2) and a corresponding function (event) for each of these states. This is how we could switch the code to the appropriate routine −switch (phase) { case 0: Lo(); break; case 1: Mid(); break; case 2: Hi(); break; default: Message("Invalid state!"); }
0 comments:
Post a Comment