C++ Switch Case
Introduction
When writing programs, you'll often need to make decisions based on the value of a variable. While if-else
statements can handle such decisions, they can become unwieldy when dealing with multiple conditions. The switch
statement provides a cleaner alternative for handling multi-way decisions based on a single expression.
The switch
statement evaluates an expression once and compares it against multiple case values to find a match and execute the corresponding code block. It's particularly useful when you need to select one option from many alternatives.
Basic Syntax
The general syntax of a switch
statement in C++ is:
switch (expression) {
case constant1:
// code to be executed if expression equals constant1
break;
case constant2:
// code to be executed if expression equals constant2
break;
// you can have any number of case statements
default:
// code to be executed if expression doesn't match any constants
}
Let's break down the components:
- switch: The keyword that starts the statement
- expression: The value to be compared (usually a variable)
- case: Defines a specific value to compare against
- constant: A literal value (like 1, 2, 'A', etc.)
- break: Exits the switch statement
- default: Optional section that executes if no case matches
How Switch Case Works
flowchart TD A[Start] --> B[Evaluate expression] B --> C[Compare with case values] C -->|case 1| D[Execute case 1 code] C -->|case 2| E[Execute case 2 code] C -->|case 3| F[Execute case 3 code] C -->|No match| G[Execute default code] D --> H[break?] E --> H F --> H G --> I[End] H -->|Yes| I H -->|No| J[Continue to next case] J --> H
Basic Examples
Example 1: Day of the Week
#include <iostream>
using namespace std;
int main() {
int day;
cout << "Enter day number (1-7): ";
cin >> day;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
default:
cout << "Invalid day number!";
}
return 0;
}
Input:
4
Output:
Thursday
Input:
9
Output:
Invalid day number!
Example 2: Simple Calculator
#include <iostream>
using namespace std;
int main() {
double num1, num2;
char operation;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter operation (+, -, *, /): ";
cin >> operation;
cout << "Enter second number: ";
cin >> num2;
switch (operation) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
if (num2 != 0)
cout << num1 << " / " << num2 << " = " << num1 / num2;
else
cout << "Division by zero is not allowed!";
break;
default:
cout << "Invalid operation!";
}
return 0;
}
Input:
10
*
5
Output:
10 * 5 = 50
Important Details About Switch Case
1. Fall-through Behavior
When you omit the break
statement, C++ will continue executing the code for all subsequent cases until it encounters a break
or reaches the end of the switch statement. This is called "fall-through" behavior.
#include <iostream>
using namespace std;
int main() {
int x = 2;
switch (x) {
case 1:
cout << "One" << endl;
// No break, so it falls through to the next case
case 2:
cout << "Two" << endl;
// No break, so it falls through to the next case
case 3:
cout << "Three" << endl;
break;
case 4:
cout << "Four" << endl;
break;
default:
cout << "Other number" << endl;
}
return 0;
}
Output:
Two
Three
Fall-through can be useful in certain scenarios, but it can also lead to bugs if used accidentally. Always include break
statements unless you explicitly want fall-through behavior.
2. Valid Types for Switch Expression
The switch expression and case values must be of integral types (int, char, enum) or of a class type with a single conversion function to an integral type. You cannot use:
- Floating-point values (float, double)
- Strings (string)
- Booleans (bool) (though they work since they convert to integers)
3. Case Values Must Be Constant Expressions
Case values must be compile-time constants:
int main() {
const int x = 5; // This is a compile-time constant
int y = 10; // This is not a compile-time constant
int value = 5;
switch (value) {
case 1 + 2: // Valid - compile-time constant expression
cout << "Three";
break;
case x: // Valid - x is a const
cout << "Five";
break;
// case y: // INVALID - y is not a compile-time constant
// cout << "Ten";
// break;
default:
cout << "Other";
}
return 0;
}
Practical Applications
Menu-Based Systems
#include <iostream>
using namespace std;
int main() {
int choice;
do {
// Display menu
cout << "\n----- STUDENT DATABASE -----\n";
cout << "1. Add new student\n";
cout << "2. View all students\n";
cout << "3. Search student\n";
cout << "4. Update student information\n";
cout << "5. Delete student\n";
cout << "0. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Adding new student...\n";
// Code to add student
break;
case 2:
cout << "Viewing all students...\n";
// Code to view students
break;
case 3:
cout << "Searching for a student...\n";
// Code to search student
break;
case 4:
cout << "Updating student information...\n";
// Code to update student
break;
case 5:
cout << "Deleting student...\n";
// Code to delete student
break;
case 0:
cout << "Exiting program. Goodbye!\n";
break;
default:
cout << "Invalid choice! Please try again.\n";
}
} while (choice != 0);
return 0;
}
State Machine Implementation
#include <iostream>
using namespace std;
enum TrafficLightState {
RED,
YELLOW,
GREEN
};
int main() {
TrafficLightState currentState = RED;
char input;
cout << "Traffic Light Simulator\n";
cout << "Press 'n' to change to next state, 'q' to quit\n";
while (true) {
// Display current state
switch (currentState) {
case RED:
cout << "Current state: RED - Stop!\n";
break;
case YELLOW:
cout << "Current state: YELLOW - Prepare to stop/go!\n";
break;
case GREEN:
cout << "Current state: GREEN - Go!\n";
break;
}
cout << "Command: ";
cin >> input;
if (input == 'q') {
break;
} else if (input == 'n') {
// Transition to next state
switch (currentState) {
case RED:
currentState = GREEN;
break;
case YELLOW:
currentState = RED;
break;
case GREEN:
currentState = YELLOW;
break;
}
} else {
cout << "Invalid command!\n";
}
}
cout << "Simulator ended.\n";
return 0;
}
Switch vs. If-Else
While both switch
and if-else
statements can be used for decision making, each has its advantages:
When to use Switch:
- For selecting from multiple options based on a single value
- When comparing a variable against constant values
- When readability and performance matter for many conditions
When to use If-Else:
- For logical conditions (not just equality)
- When conditions involve ranges of values
- When using non-integral types (strings, floats)
- For complex Boolean expressions
Best Practices
- Always include a
default
case to handle unexpected values - Don't forget
break
statements unless fall-through is specifically needed - Add comments when using fall-through to indicate it's intentional
- Keep case blocks short for better readability
- Consider using enums with switch statements to improve code clarity
- Be consistent with your code formatting and style
Common Pitfalls
- Missing break statements causing unintended fall-through
- Duplicate case values which will cause compilation errors
- Attempting to use non-constant expressions in case labels
- Trying to use switch with non-integral types like strings or floats
- Defining variables inside a case without using curly braces
Summary
The switch
statement in C++ is a powerful control flow mechanism for handling multi-way decisions based on a single expression. It provides a cleaner and potentially more efficient alternative to multiple if-else
statements when comparing a variable against multiple constant values.
Key points to remember:
- The switch expression must be of integral type
- Case values must be constant expressions
- Break statements prevent fall-through behavior
- Include a default case to handle unexpected values
By mastering switch statements, you can write more readable and maintainable code, especially when dealing with multiple conditions based on a single value.
Exercises
- Write a program that takes a month number (1-12) and prints the number of days in that month.
- Create a menu-driven program that converts temperatures between Celsius, Fahrenheit, and Kelvin.
- Implement a simple text-based game where the player can choose different actions using a switch statement.
- Write a program that takes a character and determines if it's a vowel, consonant, digit, or special character.
- Create a calculator that can perform basic arithmetic as well as modulus, exponent, and square root operations using a switch statement.
Additional Resources
- C++ Documentation on Switch Statements
- C++ Control Flow
- Book: "The C++ Programming Language" by Bjarne Stroustrup
- C++ Switch Statement on cplusplus.com
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)