Allows an integral expression (constant, variable, enum, or a class type with a single converstion conversion function to an integral or enumerated value) to be tested against a number of other constant or literal integral expressions.
It’s form is as follows -
Example | Result | ||
---|---|---|---|
| In this example the message “Index could be 2 or 3” is printed. Notice the use the variable “index” in multiple places. It’s very easy for these statements to become unwieldly. | ||
| In this example the message “Index could be 2 or 3” is printed. Switch statements are fairly efficient tests for if conditions. The compiler is smart enough to generate code so that each case statement is not tested. When a break statement is hit (lines 6, 9, 11, and 13), program execution jumps to the end of the code block (line 34). The break statement is taken directly from the C/C++ language and is mandatory in the default statement but not in the other statements as shown in the code sample. The order of the case statements is flexible, but default must be the last statement if used. |
Info |
---|
FAQ: Why can't I use other comparisons other than the implicit == within each branch of a switch statement? The switch statement is only suitable for discreet == comparisons -- if you want more flexibility, you must choose to use full if ... else if ... else notation. FAQ: Does it matter what order I specify the branches in? No! (except default must come last). |