The switch case statement is a handy tool for handling multiple cases in a concise way. It allows us to compare an expression with different cases and execute code blocks based on the matching case.
Let's take a closer look at the syntax of the switch case statement:
Here's how the switch statement works:
- The expression is evaluated once. - The value of the expression is then compared with the values of each case. - If there is a match, the corresponding block of code is executed. - The break keyword is used to exit the switch statement after executing the code block. Without the break, execution will "fall through" to the next case, executing the code there as well. - If none of the cases match the expression's value, the code inside the default block is executed.