Switch Statement in C++

When you are learning how to code in C++ step by step, you will eventually face a situation where your code needs to make a choice between many different options. While you could use a long chain of if-else statements, there is a cleaner, more professional way: the Switch Statement.

In this post, we’ll break down the C++ Switch statement—a powerful control structure used for “multi-way branching”. Whether you are a total beginner or a student looking to refine your skills, these lecture notes will help you master selection statements.

Definitions: Understanding the Basics

Before we dive into the logic, let’s define our key terms in the simplest words possible:

Terms Used Definitions
Switch Statement A tool that allows a program to choose one path of execution from many different options based on the value of a variable.
Selector (Expression) The specific variable or value we are “checking” inside the switch brackets.
Case A specific “label” or value that the program compares against the selector.
Break Keyword (break;) A “stop” command that tells the program to exit the switch block once a task is finished.
Default Keyword (default:) The “backup” plan that runs only if none of the other cases match.
Fall-through A situation where the program continues to execute the next case because a break statement was missing.
Constant Expression A fixed value (like 1, 5, or ‘A’) that cannot change during the program’s execution.

 

The Syntax: How to Write a Switch Statement

The basic structure of a switch statement looks like this:

switch (selector) {
    case constant1:
        // code to execute
        break;
    case constant2:
        // code to execute
        break;
    .
    .
    .
    .
    default:
        // code if no cases match
}

Key Rules for the Selector:

  1. The expression inside the switch must be an integer or a type that behaves like an integer, such as a character (char).
  2. Why characters? Characters are treated as integers because they have underlying ASCII values.
  3. In modern C++ (like C++17), strings can sometimes be used in advanced ways, but for beginners, stick to integers and characters.

 

The “Break” and “Default” Keywords

The Power of break

The break statement is crucial. In an if-else structure, once a condition is met, the rest are skipped automatically. In a switch, if you don’t include a break, the program will “fall through” and execute every single case below the matching one until it hits a break or the end of the switch.
For example: The Elevator Imagine an elevator. You press “Floor 3” (the selector). The elevator checks Case 1, Case 2, and finds Case 3. It stops and opens the doors (break). If the doors didn’t open and it just kept going to Floor 4 and 5, that would be fall-through!

The Safety of default

The default case is like the final else in an if-else chain. If the user enters a value that doesn’t match any of your cases, the default section ensures the program still does something useful, like displaying an error message.

 

Relatable Daily Life Example: The Vending Machine

Imagine you are using a vending machine.

  • The Selector: The number you type on the keypad (e.g., 10, 11, 12).
  • Case 10: If you type 10, you get Potato Chips. (Break — you stop and take your chips).
  • Case 11: If you type 11, you get Chocolate. (Break — you stop and take your chocolate).
  • Default: If you type 99 (and there is no item 99), the machine displays “Invalid Selection.”

Examples

To help you apply what you’ve learned, here are three complete code examples based on the concepts discussed in the sources. These examples range from basic integer comparison to more advanced logic like character handling and range mapping.

Example 1: Basic Integer Comparison

This program demonstrates the simplest use of a switch statement. It takes an integer input from the user and compares it against specific constant values. This is more efficient and readable than a long chain of if-else statements for exact matches.

#include <iostream>
using namespace std;
int main() {
    int x;
    cout << "Enter a number (1 or 2): ";
    cin >> x;
    // The variable 'x' acts as the selector
    switch (x) {
        case 1:
            cout << "You entered one!" << endl;
            break; // Exits the switch after finding a match
        case 2:
            cout << "You entered two!" << endl;
            break;
        default:
            cout << "Number is not 1 or 2." << endl; // Runs if no cases match
    }
    return 0;
}

 

Example 2: The Vowel Finder (Using Characters)

In C++, characters can be used in switch statements because they are treated as integers based on their ASCII values. This example also uses “fall-through” logic, where multiple cases (like ‘a’ and ‘A’) lead to the same outcome because no break is placed between them.

#include <iostream>
using namespace std;
int main() {
    char ch;
    cout << "Enter any alphabet: ";
    cin >> ch;
    switch (ch) {
        // Multiple cases share the same block of code [10]
        case 'a': case 'A':
        case 'e': case 'E':
        case 'i': case 'I':
        case 'o': case 'O':
        case 'u': case 'U':
            cout << ch << " is a vowel." << endl;
            break;
        default:
            cout << ch << " is not a vowel." << endl;
    }
    return 0;
}

Example 3: Professional Grade Calculator

This advanced example shows how to handle ranges of numbers (like 90–100) in a switch statement, which normally only looks for exact values. By dividing the user’s marks by 10, we create a “Grade Group” that fits perfectly into simple cases. For instance, any score from 90 to 99 divided by 10 equals 9.

#include <iostream>
using namespace std;
int main() {
    int marks;
    cout << "Enter your marks (0-100): ";
    cin >> marks;
    // Safety check for negative numbers [15]
    if (marks < 0) {
        cout << "Invalid marks entered!" << endl;
        return 0; // Terminate the program early [16]
    }
    // Mathematical trick: divide by 10 to create manageable groups [12, 13]
    int gradeGroup = marks / 10;
    switch (gradeGroup) {
        case 10: // For 100 marks
        case 9:  // For 90-99 marks [14, 17]
            cout << "Grade: A+" << endl;
            break;
        case 8:  // For 80-89 marks [18]
            cout << "Grade: A" << endl;
            break;
        case 5:  // For 50-59 marks [18]
            cout << "Grade: D" << endl;
            break;
        default: // For any group below 5 (Fail) [18, 19]
            cout << "Grade: F" << endl;
    }
    return 0;
}

Why Use Switch Instead of If-Else?

While if-else is great for complex logical expressions (like x > 10 && y < 20), the switch statement is much cleaner and easier to read when you are comparing a single variable against many fixed values. It makes your code look professional and organized.

Interactive Elements: Try It Yourself!

  1. Reflection Prompt: Why do you think C++ requires the switch expression to be an integer or character rather than a decimal (float)?
  2. Coding Challenge 1: Write a program that asks for a number (1-7) and prints the corresponding day of the week (e.g., 1 = Monday). Don’t forget the default case for invalid numbers!
  3. Coding Challenge 2: Create a simple calculator where a user enters two numbers and an operator (+, -, *, /). Use a switch on the operator character to perform the math.
  4.  The Monthly Days Finder

    Ask the user to enter the number of a month (1–12). Use a switch statement to output how many days are in that month.

    • Efficiency Trick: Group months with 31 days together and months with 30 days together using case stacking to keep the code concise.

    • Advanced: Ask for the year as well and use an if statement inside case 2 to check for leap years.

Engagement Boost: Let’s Talk!

  • What is your biggest fear when it comes to learning C++?
  • Have you ever accidentally forgotten a break statement and had your code “fall through”? Tell us your story in the comments!

Ready to Dive Deeper?

If you found these notes helpful, make sure to:

  • Practice: Code the grade calculator mentioned above to see how division helps manage ranges.

For more official details, you can always check out the ISO C++ Standard Documentation.

Happy Coding!