🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

C++ Switch Case

C++ Switch Statement Overview

Switch Statement in C++:

In C++, the switch statement is used for decision-making based on the value of an expression. It provides a way to execute different code blocks for different values of the expression. Here's the basic syntax:


switch (expression) {
    case value1:
        // Code to execute if expression equals value1
        break;

    case value2:
        // Code to execute if expression equals value2
        break;

    // ... additional cases

    default:
        // Code to execute if expression doesn't match any case
}

Here's an example illustrating the use of the switch statement:


#include <iostream>

int main() {
    char grade;

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

    switch (grade) {
        case 'A':
            std::cout << "Excellent!" << std::endl;
            break;

        case 'B':
            std::cout << "Good job!" << std::endl;
            break;

        case 'C':
            std::cout << "Satisfactory." << std::endl;
            break;

        case 'D':
            std::cout << "Needs improvement." << std::endl;
            break;

        case 'F':
            std::cout << "Failed." << std::endl;
            break;

        default:
            std::cout << "Invalid grade." << std::endl;
    }

    return 0;
}

In this example, the program prompts the user to enter a grade (A, B, C, D, or F). The switch statement then checks the value of the grade variable and executes the corresponding code block.

A few key points about the switch statement:

  • Each case must end with a break statement to exit the switch block. Without break, the control will "fall through" to the next case.
  • The default case is optional and is executed if none of the case values match the expression.
  • The expression within the switch statement can be of integral or enumerated type. C++17 allows using switch with std::string.

It's worth noting that switch statements are often used when there are multiple values to check against a single expression. If you're dealing with ranges or more complex conditions, if-else if-else statements might be more suitable.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.