The switch statement is more concise and clear when you need to determine the equivalence of options. For example, the first four prizes are given based on the exam rankings. The first prize is a notebook, the second prize is IPAD 2, the third prize is a mobile power supply, and the last prize is a U Drive.
Syntax:
Execution process: when the value of the expression after the switch is the same as the value after the case statement, execute downward from this position until the break statement or switch statement block ends; if no matching case statement exists, the code of the default block is executed.
For example:
Some tips:
1. The expression value must beInteger or numeric type
2. Values after caseIt can be a constant value., Such as 1 and 2; alsoIt can be a constant expression., Such as 2 + 2; but cannot be a variable or an expression with a variable, such as a * 2
3. After case matching, execute the program code in the matching block.BreakWill continue to execute the content of the next case block until the break statement or switch statement block ends, as shown in
,
Running result:
4. You can combine case statements with the same functions, as shown in figure
5. The default block can appear inAny location, AlsoCan be omitted