Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    C++ switch Statements

    The C++ switch Statement selects a code block to be executed from multiple code blocks based on the condition being evaluated once. This tutorial will teach you how to use the switch Statements in C++.

    The standard format of the switch statement is:

    Syntax:

    switch(variable)
    {
        case 1:
        //execute your code
        break;
    
        case n:
        //execute your code
        break;
    
        default:
        //execute your code
    }

    After the end of each case block within a switch, it is necessary to insert a break statement because if programmers do not use the break statement, all blocks will execute continuously in every case, even after the case block is matched.

    An example of a C++ program to demonstrate a switch statement:

    Example:

    #include <iostream>
    using namespace std;
    main()
    {
        int a;
        cout << "Please enter a no between 1 and 5: " << endl; cin >> a;
    
        switch(a)
        {
            case 1:
            cout << "You chose One" << endl;
            break;
    
            case 2:
            cout << "You chose Two" << endl;
            break;
    
            case 3:
            cout << "You chose Three" << endl;
            break;
    
            case 4:
            cout << "You chose Four" << endl;
            break;
    
            case 5:
            cout << "You chose Five" << endl;
            break;
            
            default :
            cout << "Invalid Choice. Enter a no between 1 and 5" << endl;
        }
        system("PAUSE");
    }

    Program Output:

    cplusplus-switch

    The default case will be executed when neither case evaluates to true, and the default statement does not require a break statement.



    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.