Login    New User    Forgot Password    Help      

Switch Statements

GO TO INDEX

Switch Statements

In computer programming, a switch, case, select or inspect statement is a type of selection control mechanism that exists in most imperative programming languages
The main reasons for using a switch include improving clarity, by reducing otherwise repetitive coding, and (if the heuristics permit) also offering the potential for faster execution through easier compiler optimization in many cases. Although it is possible to chain many if-else statements together, this is difficult to read. Consider the following program: view sourceprint?

Although it is possible to chain many if-else statements together, this is difficult to read. Consider the following program:

enum Colors
{
    COLOR_BLACK,
    COLOR_WHITE,
    COLOR_RED,
    COLOR_GREEN,
    COLOR_BLUE,
};
void PrintColor(Colors eColor)
{
    using namespace std;
    if (eColor == COLOR_BLACK)
        cout << "Black";
    else if (eColor == COLOR_WHITE)
        cout << "White";
    else if (eColor == COLOR_RED)
        cout << "Red";
    else if (eColor == COLOR_GREEN)
        cout << "Green";
    else if (eColor == COLOR_BLUE)
        cout << "Blue";
    else
        cout << "Unknown";
}

Because doing if-else chains on a single variable testing for equality is so common, C++ provides an alternative conditional branching operator called a switch. Here is the same program as above in switch form:
void PrintColor(Colors eColor)
{
    using namespace std;
    switch (eColor)
    {
        case COLOR_BLACK:
            cout << "Black";
            break;
        case COLOR_WHITE:
            cout << "White";
            break;
        case COLOR_RED:
            cout << "Red";
            break;
        case COLOR_GREEN:
            cout << "Green";
            break;
        case COLOR_BLUE:
            cout << "Blue";
            break;
        default:
            cout << "Unknown";
            break;
    }
}

The overall idea behind switch statements is simple: the switch expression is evalutated to produce a value, and each case label is tested against this value for equality. If a case label matches, the statements after the case label are executed. If no case label matches the switch expression, the code under the default label is executed (if it exists).

Example:The switch

Switch Example

                               

#include < iostream·h>
int main() { int num; cout << "Enter a number from 1 to 3: "; cin >> num; switch(num) { case 1: cout << "111.\n"; break; case 2: cout << "222.\n"; break; case 3: cout << "333.\n"; break; default: cout << "You must enter either 1, 2, or 3.\n"; } return 0; }

OUTPUT

                                  
Enter a number from 1 to 3: 2
222.
                                        

GO TO INDEX