What is the purpose of the `switch` statement?
TL;DR
The switch
statement is used to execute one block of code among many based on the value of an expression. It is an alternative to using multiple if...else if
statements. The switch
statement evaluates an expression, matches the expression's value to a case
label, and executes the associated block of code. If no case
matches, the default
block is executed.
Purpose of the switch
statement
Simplifies multiple conditional checks
The switch
statement provides a cleaner and more readable way to handle multiple conditional checks compared to using multiple if...else if
statements. It is particularly useful when you need to compare the same expression against different values.
Syntax and structure
The basic syntax of a switch
statement is as follows:
How it works
- Expression evaluation: The
switch
statement evaluates the expression once. - Case matching: It compares the result of the expression to the values of each
case
label. - Code execution: If a match is found, the code associated with that
case
is executed. - Break statement: The
break
statement is used to exit theswitch
block. If omitted, the nextcase
will be executed (fall-through behavior). - Default case: The
default
case is optional and executes if no matchingcase
is found.
Example
Here is an example of a switch
statement in action:
In this example, the output will be Apple is red.
because the value of fruit
matches the case 'apple'
.
Fall-through behavior
If the break
statement is omitted, the switch
statement will continue to execute the subsequent case
blocks until it encounters a break
or the end of the switch
block. This is known as fall-through behavior.
In this example, the output will be:
This happens because there are no break
statements to stop the execution after the case 2
block.