0
0
C++programming~5 mins

Switch statement in C++

Choose your learning style9 modes available
Introduction

A switch statement helps you choose between many options easily. It makes your code cleaner when you have many choices based on one value.

When you want to run different code based on a number or character.
When you have many fixed options to check, like days of the week or menu choices.
When you want your code to be easier to read than many if-else statements.
Syntax
C++
switch (expression) {
    case constant1:
        // code to run if expression == constant1
        break;
    case constant2:
        // code to run if expression == constant2
        break;
    // more cases...
    default:
        // code to run if no case matches
        break;
}

The expression is checked once.

Each case compares the expression to a constant value.

Examples
Checks the value of day and runs code for Monday or Tuesday, or default if none match.
C++
switch (day) {
    case 1:
        // Monday
        break;
    case 2:
        // Tuesday
        break;
    default:
        // Other days
        break;
}
Uses a character to decide which message to show based on grade.
C++
char grade = 'B';
switch (grade) {
    case 'A':
        // Excellent
        break;
    case 'B':
        // Good
        break;
    default:
        // Other grades
        break;
}
Sample Program

This program checks the value of number. It prints a message for 1, 2, or 3. If the number is not 1, 2, or 3, it prints a default message.

C++
#include <iostream>

int main() {
    int number = 2;
    switch (number) {
        case 1:
            std::cout << "Number is one\n";
            break;
        case 2:
            std::cout << "Number is two\n";
            break;
        case 3:
            std::cout << "Number is three\n";
            break;
        default:
            std::cout << "Number is something else\n";
            break;
    }
    return 0;
}
OutputSuccess
Important Notes

Always use break; to stop the switch after a case runs, or all following cases will run too.

The default case is optional but useful for unexpected values.

Switch works best with simple values like integers or characters, not complex types.

Summary

Switch lets you pick code to run based on one value.

Use case for each choice and break; to stop.

Include default to handle unexpected values.