Home » Switch Case In C++

Switch Case In C++

Switch Case In C++

Introduction

The switch case in C++ provides a way to dispatch execution to different parts of your code based on the value of an expression. It is a control flow statement that is particularly useful when you have multiple possible values for a single variable and want to execute different code blocks based on those values. This makes it an alternative to using multiple if-else statements, offering a more readable and organized structure for certain types of problems.

Basic Structure of Switch Case In C++

The basic structure of a switch statement is as follows:


switch (expression) {
    case constant1:
        // code to be executed if expression equals constant1
        break;
    case constant2:
        // code to be executed if expression equals constant2
        break;
    // You can have any number of case statements
    default:
        // code to be executed if none of the cases match
}
C++

Here, the expression is evaluated once and compared with each case label. If a match is found, the code associated with that case is executed until a break statement is encountered, which exits the switch statement. If no match is found, the default block is executed, if it is present. The break statement is essential to prevent “fall through” where subsequent cases are executed even if they do not match.

Key Points

  • Expression: The value being evaluated in the switch statement. It must be of an integral or enumeration type.
  • Case Labels: Each case label must be a constant expression. These labels are compared against the value of the expression.
  • Break Statement: The break statement prevents the execution from falling through to subsequent cases. Without it, all subsequent cases are executed regardless of their labels.
  • Default Case: The default case is optional but recommended. It provides a fallback when none of the specified cases match the expression.

Flowchart of Switch Statement in C++

Use of Switch Case

Examples of Switch Statement In C++

Example 1: Basic Day of the Week


#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;
        case 4:
            cout << "Thursday" << endl;
            break;
        case 5:
            cout << "Friday" << endl;
            break;
        case 6:
            cout << "Saturday" << endl;
            break;
        case 7:
            cout << "Sunday" << endl;
            break;
        default:
            cout << "Invalid day" << endl;
    }

    return 0;
}

C++

Example 2: Simple Calculator


#include <iostream>using namespace std;

int main() {
    char operation;
    double num1, num2;

    cout << "Enter operator (+, -, *, /): ";
    cin >> operation;
    cout << "Enter two operands: ";
    cin >> num1 >> num2;

    switch (operation) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
            break;
        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
            break;
        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2 << endl;
            break;
        case '/':
            if (num2 != 0)
                cout << num1 << " / " << num2 << " = " << num1 / num2 << endl;
            else
                cout << "Division by zero error!" << endl;
            break;
        default:
            cout << "Invalid operator" << endl;
    }

    return 0;
}

C++
Example 3: Grade Evaluation

#include <iostream>using namespace std;

int main() {
    char grade;

    cout << "Enter your grade (A, B, C, D, F): ";
    cin >> grade;

    switch (grade) {
        case 'A':
            cout << "Excellent!" << endl;
            break;
        case 'B':
            cout << "Good job!" << endl;
            break;
        case 'C':
            cout << "Well done" << endl;
            break;
        case 'D':
            cout << "You passed" << endl;
            break;
        case 'F':
            cout << "Better try again" << endl;
            break;
        default:
            cout << "Invalid grade" << endl;
    }

    return 0;
}

C++
Example 4: Month Days Calculation

#include <iostream>using namespace std;

int main() {
    int month;

    cout << "Enter month number (1-12): ";
    cin >> month;

    switch (month) {
        case 1: case 3: case 5: case 7: case 8: case 10: case 12:
            cout << "31 days" << endl;
            break;
        case 4: case 6: case 9: case 11:
            cout << "30 days" << endl;
            break;
        case 2:
            cout << "28 or 29 days" << endl;
            break;
        default:
            cout << "Invalid month" << endl;
    }

    return 0;
}

C++

Conclusion

In conclusion, the C++ switch statement is a flexible construct that makes it easier for programs to handle a variety of scenarios. Its explicit case labels and succinct syntax make code easier to comprehend and maintain, especially in situations when there are many possible outcomes. The switch statement improves the organization of program logic by offering a direct mapping between cases and actions.

The switch statement has advantages over an if-else-if ladder in terms of performance since the compiler can optimize it for quicker execution. Developers should be aware of its restrictions, such as the need for integral or enumeration expression types and constant case values.

It is advised to provide a default case in the switch statement to manage mismatched circumstances and use it efficiently and gently. Programmers may take advantage of the switch statement’s advantages to create better organized, effective, and understandable C++ code by following best practices and comprehending its intricacies.

Frequently Asked Questions

1. What is a switch statement in C++?

A switch statement is a control flow statement that allows you to execute different blocks of code based on the value of a single expression. It is an alternative to using multiple if-else statements, providing a clearer and more concise way to handle multiple potential values for a variable.

2. What types of values can be used in a switch statement?

The expression in a switch statement must be of an integral or enumeration type. This includes int, char, and enum types. Floating-point types (float, double) and complex data types are not allowed.

3. How does the switch statement work?

The switch statement evaluates the expression and compares its value to the constants specified in the case labels. When a match is found, the code associated with that case is executed until a break statement is encountered. If no match is found, the default block is executed, if it is present.

4. What is the purpose of the break statement in a switch?

The break statement exits the switch statement, preventing the execution from falling through to subsequent cases. Without a break statement, the program continues to execute the code for all subsequent cases, regardless of whether they match the expression.