The Selective Structure : switch

The syntax of the switch instruction is a bit peculiar. Its objective is to check several possible constant values for an expression, something similar to what we did at the beginning of this section with the linking of several if and else if sentences. Its form is the following:

switch (expression)

{

case constant1:

block of instructions 1

break;

case constant2:

block of instructions 2

break;

.

.

.

default:

default block of instructions

}

It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes block of instructions 1 until it finds the break keyword, then the program will jump to the end of the switch selective structure.

If expression was not equal to constant1 it will check if expression is equivalent to constant2. If it is, it will execute block of instructions 2 until it finds the break keyword.

Finally, if the value of expression has not matched any of the previously specified constants (you may specify as many case sentences as values you want to check), the program will execute the instructions included in the default: section, if this one exists, since it is optional.

Switch Example

switch (x)

{

case 1:

cout << "x is 1";

break;

case 2:

cout << "x is 2";

break;

default:

cout << "value of x unknown";

}

if-else equivalent

if (x == 1) {

cout << "x is 1";

}

else if (x == 2) {

cout << "x is 2";

}

else {

cout << "value of x unknown";

}

Notice the inclusion of the break instructions at the end of each block. This is necessary because if, for example, we did not include it after block of instructions 1 the program would not jump to the end of the switch selective block (}) and it would continue executing the rest of the blocks of instructions until the first appearance of the break instruction or the end of the switch selective block. This makes it unnecessary to include curly brackets { } in each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression evaluated. For example:

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"; }

Notice that switch can only be used to compare an expression with different constants. Therefore we cannot put variables (case (n*2):) or ranges (case (1..3):) because they are not valid constants.

HOME LEARN C++ PREVIOUS NEXT