Using the switch Statement
Imagine you're buying a soda from a vending machine. After you select your desired drink, deep within the vending machine's computer, the
user_input variable takes on one of several predefined values. Each of these options is termed a
case, and this is where the
switch statement comes into play.
Think of the
switch statement as another version of the
if-else statement. It acts in response to specific values you've previously defined.
Here's how the structure of a
switch statement looks:
Let's consider a vending machine example. Suppose there are three buttons to select different types of chips:
- Cheese-flavored chips
- Bacon-flavored chips
- Chili-flavored chips
If the tested expression doesn't match any of the listed cases, the
default case is executed. If there's no
default case provided, the program simply continues its flow.
The tested expression in a
switchstatement can only be of integer or
chartype. You can't use variables, strings, or non-integer data types as cases.
The Role of break
break command stops the current block's execution and moves on to the next segment of code. Essentially, once the relevant case is complete, you exit that block and continue with your program.
break command, the
switch statement would run continuously, and you'd likely end up with unintended results.
In the absence of the
break command, the program starts executing immediately after finding a matching case and continues until it finds a break or reaches the end of the switch.
Everything was clear?