Loading

The Switch Statement (Case)

12/2/2015
The Switch Statement (Case)

Interested in learning the C++ programming language? Try doing it with One Hour a Day.

The switch statement is similar to the if statement in a way that it determines what the program should do depending on certain conditions. It can also be used to control the flow of program. But the way it is built follows a different approach and, unlike the if statement, the switch statement allows for multiple cases or tests to yield the same outcome.

switch (myVariable)
{
    case myFirstCaseValue:
        // do these statements
        break;

    case mySecondCaseValue:
        // do these statements
        break;

    // and so on ...

    case myLastCaseValue:
        // do these statements
        break;

    default:
        // do these statements if no cases were matched (i.e. default behavior)
}

The way the switch traditionally works is like this: you give it an integer expression within the parenthesis (usually a variable). Then the program starts checking for each case that matches that particular case value with the value that was given to the switch statement. If the value of the case matches (that is, is equal to) the same value as the given integer expression in the parenthesis, then it will execute those statements under the case and will ONLY stop when it finds a break statement. The presence of the break is crucial for your switch statement to stop and yield proper behavior, so do not forget to include a break after listing all the statements that should be executed for each case.

Some programming languages other than C++ allow for the expression under switch (expression) to be something other than an integer value. PHP, for instance, allows the use of strings as the argument for the switch statement. With that, your cases can be string values instead of just integer values.

int myIntegerVariable;

myIntegerVariable = 3;

switch (myIntegerVariable)
{
case 1:
  cout << "Action #1" << endl;
  break;

case 2:
  cout << "Action #2" << endl;
  break;

case 3:
  cout << "Action #3" << endl;
  break;

default:
  cout << "Default Action" << endl;

}

Output:

Action #3

First we declare an integer value. Then we assign the value 3 to the integer variable. Next, the switch takes the integer value as its expression and then starts going through the cases. First, it checks the first case: does myIntegerVariable hold the value 1? No, because myIntegerVariable holds the integer 3. It then skips to the next case: does myIntegerVariable hold the value 2? No. Then, the next case: does myIntegerVariable hold the value 3? Yes. Because the values matched, the statements under "case 3:" are executed: it simply displays a message, "Action #3." The program will continue executing statements as long as there is no break statement, so we have to make sure there is a break so the switch statement is terminated and the program goes on to do other stuff.

Had we made the integer variable in the above example hold a case that is not 1, 2, nor 3, then it would default to the default case, which appears at the end, right before the closing brace. In a way, that is like the "else" of an if statement, when all the conditions have failed to be true.

Keep in the mind that the expression given to the switch statement, in C++, has to be an integer, and that the values for the "case X" have to be constant values (no variables allowed!). However, programming languages like PHP allow for the use of strings for the switch expression and cases.

As an example, the following would not work in C++:

string myGreeting;

myGreeting = "Hello";

switch (myGreeting)
{
case "Morning":
  cout << "Good morning to you, too!" << endl;
  break;

case "Hello":
  cout << "Hello, dolly!" << endl;
  break;

case "Night:":
  cout << "See you" << endl;
  break;

default:
  cout << "Good night!!" << endl;

}

Output (the compiler produces an error as output):

switch_statement.cpp: In function ‘int main()’:
switch_statement.cpp:87:21: error: switch quantity not an integer
   switch (myGreeting)

But the above construct would surely work in PHP because it allows strings to be used as the switch expression and case, unlike C++, which only allows integers to be used:

<?php

$myGreeting = "Hello";

switch ($myGreeting) {

  case "Morning":
    echo "Good morning to you, too!";
    break;

  case "Hello":
    echo "Hello, dolly!";
    break;

  case "Night":
    echo "Good night!!";
    break;

  default:
    echo "What's up?";

}

?>

Output:

Hello, dolly!

Switch expressions are typically given an enumeration ("enum") because it makes it easier to understand each case. An enum is like a label given to an integer. It looks like text, but is just a mask behind an actual integer number. For instance, you could make a list of enums that would give represent the integer values 0, 1, 2, 3 like this, using C++:

enum
{
    MY_FIRST_ENUM,
    MY_SECOND_ENUM,
    MY_THIRD_ENUM,
    MY_FOURTH_ENUM
};

With the above, you could use any of the enum items in place of a variable name or value. That would just mask the value behind the scenes. Had we used MY_THIRD_ENUM, we would be actually referring to the value 2 (you start counting from 0 if you use the above enumeration).

Imagine we have a game in which we are checking input from the user. Assume the user presses a key in the keyboard to move the character in the game. It would be either the up, down, left, or right arrows -- there are four cases. So we could make a switch statement to take care of that. But suppose we do not want to explicitly use integers for each case part. Instead, we could use an enum to mask those numbers and make us better understand the code we are writing:

// An enumeration for the keyboard keys
// Each gets associated with an integer value, starting from 0 going to 1, 2, 3, etc.
enum
{
    KEY_UP,
    KEY_DOWN,
    KEY_LEFT,
    KEY_RIGHT
}

// Assume we got the integer value associated with
// the key press inside userKeyPress
switch (userKeyPress)
{
    case KEY_UP:
        // move up
        break;

    case KEY_DOWN;
        // move down
        break;

    case KEY_LEFT:
        // move left
        break;

    case KEY_RIGHT:
        // move right
        break;
}

The above code would translate to exactly the code below. Which one is better to understand? I think the above code is much more intuitive.

// Assume we got the integer value associated with
// the key press inside userKeyPress:
// 0 means up key was pressed
// 1 means up key was pressed
// 2 means up key was pressed
// 3 means up key was pressed

switch (userKeyPress)
{
    case 0:
        // move up
        break;

    case 1;
        // move down
        break;

    case 2:
        // move left
        break;

    case 3:
        // move right
        break;
}

To conclude this article, let us touch upon making multiple cases yield the same outcome. Remember that we had the break statement for every case ending? What if we take that out and stack cases on top of each other, all leading to the same statements? That will do exactly what you would expect: If any of those cases matched, then it would execute those very statements!

Take a look at the code below. Imagine you took some test or a class and you got your grade inside a variable called myGrade. The example below uses a character to check each case. But wait, how come a character can be used if C++ only accepts integer as the expression/case for a switch? Well, that is because a character is actually an integer value. A character is just a mask for an integer value. For instance, the character 'A' can be a representation for the value 65. So the example below will work.

char myGrade = 'C';

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

    case 'B':
        cout << "Great!" << endl;
        break;

    case 'C':
    case 'D':
        cout << "Okay..." << endl;
        break;

    case 'F':
        cout << "You totally failed!" << endl;
        break;

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

Output:

Okay...

The example checks for your grade and goes through each case. Observe we stacked case 'C' and 'D' on top of each other. That is because we want to display the same message if you got either grade C or D. So two cases are yielding the same outcome -- the same message. You can stack as many cases as you want. The secret to this is that once a case is matched, the program keeps executing statements as long as there is no break. Had the case been 'C' in the above example, then it would match there and everything below "case 'C':" would get executed up to the point where a break command was found, signaling the switch operation to terminate. That is, it will walk over to case 'D' and execute the cout with the message "Okay..." even though that case did not match.

Learning the C++ programming language? How about doing it with One Hour a Day.

Did you like the lesson? 😆👍
Consider a donation to support our work: