![]() |
VOOZH | about |
The switch statement evaluates an expression and executes code based on matching cases. It’s an efficient alternative to multiple if-else statements, improving readability when handling many conditions.
Syntax
switch (expression) {
case value1:
// Code block 1
break;
case value2:
// Code block 2
break;
// more cases
default:
// Default code block
}
Flowchart of Switch Statement:
For Example:
Output
WednesdayIn this example
The default keyword in a switch statement is used as a fallback option when none of the case labels match the evaluated value. It functions similarly to an else in an if-else chain, ensuring that a default action is executed when no specific conditions are met.
For Example
Output
Day not recognized.In this example
In some situations, multiple case labels in a switch statement require the same block of code to be executed. Instead of repeating the same code for each case, we can group them together.
Here is the example of common code blocks
Output
Grade is goodIn this example
if-else | Switch |
|---|---|
Used for complex conditions and ranges. | Used for exact matches of a single value. |
Slower performance with many conditions. | Faster performance with multiple values to check. |
More flexible for complex scenarios. | Less flexible, limited to specific conditions. |
No fall-through; moves to the next else. | Can have fall-through if break is omitted. |
Uses else for the default condition. | Has a default case to handle unmatched values |