C++ Switch
Efficient multi-way decision making in C++
π What is C++ Switch?
C++ switch statement provides an efficient way to execute different code blocks based on the value of a variable, offering a cleaner alternative to multiple if-else statements.
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
default:
cout << "Other day" << endl;
}
return 0;
}
Output:
Wednesday
Key Switch Concepts
Case Labels
Define different execution paths
case 1:
// code for case 1
break;
Break Statement
Exit the switch after execution
case 2:
cout << "Two";
break;
Default Case
Handle unmatched values
default:
cout << "Unknown";
break;
Fall Through
Execute multiple cases
case 1:
case 2:
// both execute
πΉ Basic Switch Statement
The switch statement selects one of many code blocks to execute based on an integral
expression's value. It consists of the switch(expression) header followed by
case labels and an optional default. Each case represents a possible value;
execution jumps to the matching case. Unlike if-else chains, switch is often
more readable for multiple discrete values. Remember that case values must be constant expressions, and
you typically need break after each block to prevent fall-through.
#include <iostream>
using namespace std;
int main() {
char grade = 'B';
switch (grade) {
case 'A':
cout << "Excellent!" << endl;
break;
case 'B':
cout << "Good job!" << endl;
break;
case 'C':
cout << "Average" << endl;
break;
case 'D':
cout << "Below average" << endl;
break;
case 'F':
cout << "Failed" << endl;
break;
default:
cout << "Invalid grade" << endl;
}
return 0;
}
Output:
Good job!
πΉ Switch with Numbers
Using switch with numeric values is common in menus, state machines, and simple
calculators. The expression (in parentheses) is evaluated, and control transfers to the
case with the matching constant. For a calculator, case '+': result = a + b; break;.
Ensure you handle the default case for invalid inputs. Numeric switch is efficient because
compilers can optimize it into jump tables. However, it only works with integral types (int,
char, enum), not floats or strings.
#include <iostream>
using namespace std;
int main() {
int choice = 2;
int a = 10, b = 5;
switch (choice) {
case 1:
cout << "Addition: " << (a + b) << endl;
break;
case 2:
cout << "Subtraction: " << (a - b) << endl;
break;
case 3:
cout << "Multiplication: " << (a * b) << endl;
break;
case 4:
cout << "Division: " << (a / b) << endl;
break;
default:
cout << "Invalid operation" << endl;
}
return 0;
}
Output:
Subtraction: 5
πΉ Fall Through Behavior
Fall-through occurs in a switch when a case block lacks a break
statement, causing execution to continue into the next case. This is sometimes intentional
to share code for multiple values, like grouping several cases that should perform the same action. For example,
case 1: case 2: cout << "Small"; break;. Unintentional fall-through is a common bug, so many
compilers issue warnings. Use [[fallthrough]] attribute (C++17) to document intentional fall-through
and silence warnings.
#include <iostream>
using namespace std;
int main() {
int month = 12;
switch (month) {
case 12:
case 1:
case 2:
cout << "Winter season" << endl;
break;
case 3:
case 4:
case 5:
cout << "Spring season" << endl;
break;
case 6:
case 7:
case 8:
cout << "Summer season" << endl;
break;
case 9:
case 10:
case 11:
cout << "Fall season" << endl;
break;
default:
cout << "Invalid month" << endl;
}
return 0;
}
Output:
Winter season
πΉ Switch vs If-Else
switch and if-else both handle conditional logic but suit different
scenarios. Use switch for comparing a single variable against multiple constant values
(integers, enums, chars). Itβs often more readable and can be optimized by the compiler. Use if-else
for complex conditions involving ranges, relational operators (>, <), multiple
variables, or non-integral types. if-else is more flexible, but switch provides cleaner
syntax for discrete value matching. Choose based on clarity and the nature of the condition.
#include <iostream>
using namespace std;
int main() {
int option = 2;
// Using switch (cleaner for multiple values)
switch (option) {
case 1: cout << "Option One"; break;
case 2: cout << "Option Two"; break;
case 3: cout << "Option Three"; break;
default: cout << "Invalid option";
}
cout << endl;
// Equivalent if-else (more verbose)
if (option == 1) {
cout << "Option One";
} else if (option == 2) {
cout << "Option Two";
} else if (option == 3) {
cout << "Option Three";
} else {
cout << "Invalid option";
}
return 0;
}
Output:
Option Two
Option Two