Switch-case statements in C++

In C++, the switch statement is used to create multi-branching logic based on the value of an expression. It allows you to compare the value of an expression to various constant case values and execute different blocks of code based on the match.

Switch-case statements

Syntax
switch (expression) { case constant_value1: // Code to execute if expression matches constant_value1 break; case constant_value2: // Code to execute if expression matches constant_value2 break; // ... default: // Code to execute if none of the case values match the expression }

The expression is evaluated, and the program jumps to the case that matches the expression. If no case matches, the code in the default block (optional) is executed.

Example
int day = 3; switch (day) { case 1: std::cout << "Monday" << std::endl; break; case 2: std::cout << "Tuesday" << std::endl; break; case 3: std::cout << "Wednesday" << std::endl; break; case 4: std::cout << "Thursday" << std::endl; break; case 5: std::cout << "Friday" << std::endl; break; default: std::cout << "Weekend" << std::endl; }

In this example, if day is equal to 3, it matches the case 3, so "Wednesday" is printed. If day were 6, it wouldn't match any case, so the code in the default block would execute, printing "Weekend."

Notes:

The break statement is used to exit the switch block after executing the code for a matched case. It prevents falling through to the next case. While break is optional, not including it can lead to unintended behavior where multiple cases execute consecutively.

The switch statement is particularly useful when you have multiple options to choose from based on the value of a single expression, making your code more readable and efficient compared to using multiple if-else if statements.

Conclusion

The switch statement is a control structure used for multi-branching based on the value of an expression. It allows you to compare the expression with a series of constant values defined in case blocks, executing the code associated with the first matching case. The default block, if present, provides a fallback option for when none of the cases match.