The syntax of the switch statement is a bit peculiar. Its purpose is to check for a value among a number of possible constant expressions. It is something similar to concatenating if-else statements, but limited to constant expressions. Its most typical syntax is:

switch (expression)
{
  case constant1:
     group-of-statements-1;
     break;
  case constant2:
     group-of-statements-2;
     break;
  .
  .
  .
  default:
     default-group-of-statements
}

 

Basically, what “Switch” actually does is to evaluate expression and checks if it is equivalent to constant1; if it is, it executes group-of-statements-1 until it finds the break statement. When it finds this break statement, the program jumps to the end of the entire switch statement (the closing brace).

If expression was not equal to constant1, it is then checked against constant2. If it is equal to this, it executes group-of-statements-2 until a break is found, when it jumps to the end of the switch. Finally, if the value of expression did not match any of the previously specified constants (there may be any number of these), the program executes the statements included after the default: label, if it exists (since it is optional). Both of the following code fragments have the same behavior, demonstrating the if-else equivalent of a switch statement:

switch example if-else equivalent

switch (x) {

  case 1:

    cout << "x is 1";

    break;

  case 2:

    cout << "x is 2";

    break;

  default:

    cout << "value of x unknown";

  }

if (x == 1) {

cout &lt;&lt; "x is 1";

}

else if (x == 2) {

cout &lt;&lt; "x is 2";

}

else {

cout &lt;&lt; "value of x unknown";

}

 

Here is a simple example of a code with a “Switch” Statement in it.

switch (x) {
  case 1:
  case 2:
  case 3:
    cout << "x is 1, 2 or 3";
    break;
  default:
    cout << "x is not 1, 2 nor 3";
  }

 

Sources:

http://en.cppreference.com/w/cpp/language/switch

http://www.cplusplus.com/doc/tutorial/control/#switch

-The Admin.

CC BY 4.0 Use of “Switch” as a Conditional. by esaupreciado is licensed under a Creative Commons Attribution 4.0 International License.