100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C++

switch Statement in C++

Master the C++ `switch` statement — matching an expression against multiple case labels, the role of break, fall-through behavior, and default.

Decision MakingBeginner8 min readJul 7, 2026
Analogies

1. Intro

The switch statement is a multi-way branch that compares a single expression against a list of constant case labels. It is typically used as a cleaner alternative to a long else if ladder when a program needs to compare one variable against many discrete, known values — such as handling a menu choice, a day number, or a grade letter.

🏏

Cricket analogy: Choosing switch over a long else if ladder is like a match referee checking a single toss-call value against known outcomes - heads, tails - instead of chaining separate condition checks for each possibility.

2. Syntax

cpp
switch (expression) {
    case value1:
        // statements
        break;
    case value2:
        // statements
        break;
    default:
        // statements executed if no case matches
}

3. Explanation

The expression must evaluate to an integral or enumeration type (int, char, enum, etc.) — it cannot be a float, double, or string in standard C++. Each case label must be a constant expression known at compile time. When switch runs, it jumps directly to the case label matching expression's value and begins executing from that point. The optional default label runs when no case matches, and may appear anywhere in the block though it is conventionally placed last.

🏏

Cricket analogy: A switch on over_number (an int) works fine like checking which specific over Bumrah is bowling, but you couldn't switch on a float strike rate - just as a bowler can't be selected by a fractional over count.

4. Example

cpp
#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 << "Invalid day" << endl;
    }

    return 0;
}

5. Output

text
Wednesday

6. Key Takeaways

  • switch matches an integral/char/enum expression against constant case labels.
  • Without a break, execution falls through into the next case regardless of its label — this is a common bug source.
  • default is optional and runs when no case matches; it can appear anywhere but is usually placed last.
  • switch cannot test ranges or floating-point/string values directly — only exact matches on integral constants.

Practice what you learned

Was this page helpful?

Topics covered

#CStudyNotes#Programming#SwitchStatementInC#Switch#Statement#Syntax#Explanation#StudyNotes#SkillVeris#ExamPrep