Local Variable Scope in the switch Body – Control Flow

Local Variable Scope in the switch Body

The scope of a local variable declared in a switch statement or a switch expression is the entire switch block. Any local block in the switch body introduces a new local scope. Any local variable declared in it has block scope, and therefore, is only accessible in that block. A local variable declared in an enclosing local scope cannot be redeclared in a nested local scope (ยง6.6, p. 354).

Summary of the switch Statement and the switch Expression

Table 4.1 summarizes the features of the switch statement and the switch expression, and provides a comparison of the two constructs.

Table 4.1 Comparing the switch Statement and the switch Expression

NotationThe switch statementThe switch expression
The colon (:) notation: case label: statementsExecutes statements associated with the matching case label.Fall-through can occur.No compile-time check for exhaustiveness.Only break and return statements allowed to control fall-through.Executes statements associated with the matching case label, but must have a yield statement to return a value.Fall-through can occur.Compile-time check for exhaustiveness.No break or return statement allowed.
The arrow (->) notation: case label -> actionAction associated with a switch rule can be an expression statement, can be a block, or can throw an exception.Mutually exclusive switch rules: no fall-through can occur.No compile-time check for exhaustiveness.break and return statements allowed.Action associated with a switch rule can be any expression, can be a block, or can throw an exception.Mutually exclusive switch rules: no fall-through can occur.Compile-time check for exhaustiveness.No break or return statement allowed.Must return a value that is either the value of a stand-alone expression or the value of the expression in a yield statement that can occur as the last statement in a block.