Learn C++ - C++ switch






Here's the general form for a switch statement:

switch (integer-expression) 
{ 
       case label1 : statement(s) 
       case label2 : statement(s) 
      ... 
       default     : statement(s) 
} 

Example


#include <iostream>
using namespace std;
void showmenu();   // function prototypes
void report();
void comfort();//  w  w  w .j  a v a 2  s  .  c o  m
int main()
{
    cout << "Please enter 1, 2, 3, 4, or 5:\n";
    int choice;
    cin >> choice;
    while (choice != 5)
    {
        switch(choice)
        {
            case 1  :   cout << "\a\n";
                        break;
            case 2  :   cout << "BBB\n";
                        break;
            case 3  :   cout << "The boss was in all day.\n";
                        break;
            case 4  :   cout << "AAA\n";
                        break;
            default :   cout << "That's not a choice.\n";
        }
        cout << "Please enter 1, 2, 3, 4, or 5:\n";
        cin >> choice;
    }
    cout << "Bye!\n";
    return 0;
}

The code above generates the following result.





Using Enumerators as Labels

The following code illustrates using enum to define a set of related constants and then using the constants in a switch statement.


#include <iostream>
using namespace std;
enum {red, orange, yellow, green, blue, violet, indigo};
//  w  w w.  jav a  2  s.  com
int main()
{
    
    cout << "Enter color code (0-6): ";
    int code;
    cin >> code;
    while (code >= red && code <= indigo)
    {
        switch (code)
        {
            case red     : cout << "red.\n"; break;
            case orange  : cout << "orange.\n"; break;
            case yellow  : cout << "yellow.\n"; break;
            case green   : cout << "green.\n"; break;
            case blue    : cout << "blue.\n"; break;
            case violet  : cout << "violet.\n"; break;
            case indigo  : cout << "indigo.\n"; break;
        }
        cout << "Enter color code (0-6): ";
        cin >> code;
    }
    return 0; 
}

The code above generates the following result.