Instead of employing numerous if…else statements, you can utilize the switch statement.
The switch statement chooses one of multiple code blocks to execute.
switch (expression) { case x: // code block break; case y: // code block break; default: // code block } |
Here’s how it functions:
The following example utilizes the weekday number to determine the corresponding weekday name:
int day = 4;
switch (day) { // Outputs “Thursday” (day 4) |
When C encounters a break keyword, it exits the switch block, halting the execution of any further code and case testing within that block.
Once a match is found and the required task is completed, it’s necessary to break out. Additional testing becomes unnecessary at that point.
Using a break can significantly save execution time since it effectively skips the execution of all remaining code within the switch block. |
The default keyword designates code to execute if no case matches are found:
int day = 4;
switch (day) { // Outputs “Looking forward to the Weekend” |
Note: The default keyword should be positioned as the final statement within the switch block, and it does not require a break statement. |