C++ Switch Statement



The Switch Condition Statement

The switch statement lets the value of a variable or expression determine where the program will branch to. A branch occurs when one part of a program causes another part to execute.

The if...else and if statement allows your program to branch into one of several possible paths. It performs a series of tests (usually relational) and branches when one of these tests is true.

The switch statement is a similar mechanism. It, however, tests the value of an integer expression and then uses that value to determine which set of statements to branch to.

Here is the format of the switch statement:


    switch (IntegerExpression)
    {
    case ConstantExpression: // Place one or more
// statements here
    case ConstantExpression: // Place one or more
// statements here
    // case statements may be repeated
    // as many times as necessary
    default: // Place one or more
// statements here
    }

The first line of the statement starts with the word switch, followed by an integer expression inside parentheses. This can be either of the following:

  • A variable of any of the integer data types (including char).
  • An expression whose value is of any of the integer data types.

This program demonstrates the use of a switch statement. The program simply tells the user what character they entered.


    #include <iostream.h>
    using namespace std;
    int main()
    {
    char choice;
    cout << "Enter A, B, or C: ";
    cin >> choice;
    switch (choice)
    {
    case 'A':cout << "You entered A.\n";
     break;
     case 'B':cout << "You entered B.\n";
     break;
     case 'C':cout << "You entered C.\n";
     break;
     default: cout << "You did not enter A, B, or C!\n";
     }
     return 0;
     }

Output with Example Input Shown in Bold:
    Enter A, B, or C: B
    You entered B.
Output with Different Example Input Shown in Bold:
    Enter A, B, or C: F
    You did not enter A, B, or C!

The first case statement is case 'A':, the second is case 'B':, and the third is case 'C':. These statements mark where the program is to branch to if the variable choice contains the values 'A', 'B', or 'C'.

The default section is branched to if the user enters anything other than A, B, or C. Notice the break statements at the end of the case 'A', case 'B', and case 'C' sections.


PROMOTIONS