Topic 14 of 83
Switch Statement
Overview
Switch statements are used when comparing a single variable against a series of constants. They are often cleaner and slightly faster than long if-else if chains.
Syntax
cpp
char grade = 'B';
switch (grade) {
case 'A':
cout << "Excellent";
break; // Crucial to prevent fall-through
case 'B':
cout << "Good";
break;
default:
cout << "Unknown grade";
}Common Pitfalls
- Forgetting the `break;` statement, causing multiple unrelated cases to execute consecutively.
- Trying to use floating-point numbers or strings as switch expressions.
Interview Tips
- Switch statements in C++ can only evaluate integral or enum types (e.g., int, char, enum). You cannot use std::string in a switch statement.
- Understand 'fall-through' behavior where omitting a 'break' causes the next case to execute.
Real-World Example
A simple menu selection system.
example
cpp
#include <iostream>
using namespace std;
int main() {
int choice = 2;
switch (choice) {
case 1: cout << "Starting game...\n"; break;
case 2: cout << "Loading settings...\n"; break;
case 3: cout << "Exiting...\n"; break;
default: cout << "Invalid selection.\n";
}
return 0;
}