int month = 4;
switch (month) {
case 4:
case 6:
case 9:
case 11:
cout << "30 days" << endl; // April falls through to here
break;
case 2:
cout << "28 or 29 days" << endl;
break;
default:
cout << "31 days" << endl;
}
Output:
30 days
Note: The switch expression must evaluate to an integer or char type. You cannot use string in a switch statement in C++.
Exercise
Write a switch-based calculator: read two numbers and an operator (+, -, *, /), then print the result.
Show Solution
#include <iostream>
using namespace std;
int main() {
double a, b;
char op;
cout << "Enter: num op num (e.g. 5 + 3): ";
cin >> a >> op >> b;
switch (op) {
case '+': cout << a + b; break;
case '-': cout << a - b; break;
case '*': cout << a * b; break;
case '/':
if (b != 0) cout << a / b;
else cout << "Error: divide by zero";
break;
default: cout << "Unknown operator";
}
cout << endl;
return 0;
}
Quiz
What does break do inside a switch?
A) Ends the entire program
B) Skips the current case
C) Exits the switch block
D) Goes to the default case
Answer
C)break exits the switch block, preventing fall-through to the next case.
Can you use a string in a C++ switch expression?
A) Yes, always
B) Only with C++20
C) No, only integer and char types
D) Only with a compiler flag
Answer
C) C++ switch only works with integral types (int, char, enum).
Summary
switch matches an integer/char expression against case values.
Always use break to prevent unintended fall-through.
default handles values that match no case.
Multiple cases can share code by stacking them without break.