Switch-Case

Multi-way branching with switch

Interview Relevant: Alternative to if-else chains

Switch-Case Statements

Switch provides multi-way branching based on a value.

Key Points

  • Works with integral and enum types
  • Case labels must be constant expressions
  • break prevents fall-through
  • default handles unmatched cases
  • C++17 adds [[fallthrough]] attribute

Code Examples

Using switch-case for multi-way branching.

cpp
1int day = 3;
2
3switch (day) {
4    case 1:
5        cout << "Monday" << endl;
6        break;
7    case 2:
8        cout << "Tuesday" << endl;
9        break;
10    case 3:
11        cout << "Wednesday" << endl;
12        break;
13    default:
14        cout << "Other day" << endl;
15        break;
16}
17
18// Multiple cases
19switch (day) {
20    case 1:
21    case 2:
22    case 3:
23    case 4:
24    case 5:
25        cout << "Weekday" << endl;
26        break;
27    case 6:
28    case 7:
29        cout << "Weekend" << endl;
30        break;
31}
32
33// C++17: switch with initializer
34switch (auto ch = getchar(); ch) {
35    case 'y': cout << "Yes"; break;
36    case 'n': cout << "No"; break;
37    default: cout << "Unknown"; break;
38}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In