YouTip LogoYouTip

Cpp Switch

# C++ switch Statement In C++, a `switch` statement is a control flow statement used to execute different blocks of code based on the value of an expression. It is commonly used as a cleaner, more readable alternative to a long chain of `if-else if-else` statements. A `switch` statement allows a variable or expression to be tested for equality against a list of values, each of which is called a **case**. The compiler checks the expression against each case sequentially. --- ## Syntax The syntax for a `switch` statement in C++ is as follows: ```cpp switch(expression) { case constant_expression_1: statement(s); break; // Optional case constant_expression_2: statement(s); break; // Optional // You can have any number of case statements default: // Optional statement(s); } ``` ### Rules and Requirements To use a `switch` statement correctly in C++, you must adhere to the following rules: * **Expression Type:** The `expression` inside the `switch` parentheses must evaluate to an **integral** or **enumeration** type, or a class type that has a single conversion function to an integral or enumeration type. Floating-point numbers (e.g., `float`, `double`) and strings are **not** allowed. * **Case Constants:** The `constant_expression` following a `case` must be of the same data type as the switch expression, and it must be a **constant** or a **literal** (e.g., `4`, `'A'`, or a `const` variable). You cannot use variables that can change at runtime. * **Execution Flow:** When the switch expression matches a case constant, the statements following that case will execute until a `break` statement is encountered. * **The Role of `break`:** When a `break` statement is reached, the `switch` terminates, and control flow jumps to the line immediately following the entire switch block. * **Fall-Through Behavior:** The `break` statement is optional. If you omit `break` at the end of a case, execution will "fall through" and continue executing the statements in the subsequent cases, regardless of whether they match the expression, until a `break` or the end of the switch is reached. * **The `default` Case:** You can include an optional `default` case at the end of the switch block. The `default` case executes if none of the explicit cases match the expression. No `break` is required for the `default` case if it is placed at the very end. --- ## Control Flow Diagram ``` | +----------------+----------------+ | | Matches Case 1? Matches Case 2? | | | | Has 'break'? Has 'break'? | +--------+ | +--------+ | | | | | (Fall-through) | (Fall-through) | v | v | | | | | | +--------+-------+ +--------+-------+ | | v v ``` --- ## Code Examples ### Example 1: Basic Integer Switch The following example demonstrates a simple switch statement using an integer variable to print the corresponding day of the week. ```cpp #include int main() { int day = 4; 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; case 6: std::cout << "Saturday" << std::endl; break; case 7: std::cout << "Sunday" << std::endl; break; default: std::cout << "Invalid day" << std::endl; } return 0; } ``` **Output:** ```text Thursday ``` --- ### Example 2: Switch with Character Type Because characters (`char`) are internally represented as integers (ASCII values), they can be used in switch statements. ```cpp #include using namespace namespace std; int main () { // Local variable declaration char grade = 'D'; switch(grade) { case 'A' : cout << "Excellent!" << endl; break; case 'B' : case 'C' : cout << "Well done" << endl; break; case 'D' : cout << "You passed" << endl; break; case 'F' : cout << "Better try again" << endl; break; default : cout << "Invalid grade" << endl; } cout << "Your grade is " << grade << endl; return 0; } ``` **Output:** ```text You passed Your grade is D ``` --- ### Example 3: Intentional Fall-Through Sometimes, you may want multiple cases to execute the exact same block of code. You can achieve this by stacking cases together without `break` statements. ```cpp #include int main() { int number = 2; switch (number) { case 1: std::cout << "Number is 1" << std::endl; break; case 2: // Fall-through case 3: std::cout << "Number is 2 or 3" << std::endl; break; default: std::cout << "Number is not 1, 2, or 3" << std::endl; } return 0; } ``` **Output:** ```text Number is 2 or 3 ``` --- ## Key Considerations * **The Fall-Through Pitfall:** Forgetting a `break` statement is one of the most common bugs in C++ switch statements. If you omit it, the program will continue executing subsequent cases even if they do not match. If you intend to use fall-through, it is good practice to add a comment like `// fallthrough` (or use the C++17 attribute `[];`) to let other developers know it was intentional. * **The `default` Case Placement:** Although the `default` case is typically placed at the end of the switch block, it can technically be placed anywhere. However, keeping it at the end is standard practice for readability. * **Variable Declarations Inside Cases:** If you need to declare and initialize a new variable inside a `case` block, you must wrap the case's statements in curly braces `{}` to limit the variable's scope. Otherwise, the compiler will throw an error because the variable's scope would span across other cases. ```cpp switch (value) { case 1: { int temp = 10; // Allowed because of the explicit block scope std::cout << temp << std::endl; break; } case 2: // temp is not accessible here break; } ```
← Cpp Pointer ArithmeticCpp If Else β†’