Switch-Case control statements

In addition to two-way selection, most programming languages provide another selection concept known as multi-way selection.

Multi-way selection chooses among several alternatives. C++ has two different ways to implement multi-way selection. The switch statement and else-if construct If for suppose we have more than one valid choices to choose from then we can use switch statement in place of if statements.

Syntax:

switch(expression)
{.
case value-1:
     block-1
     break;
case value-2:
     block-2
     break;
--------
--------
default:
    default block;
    break;
}

As you can see in the above scheme the case and default have a “break;” statement at the end of block.

This expression will cause the program to exit from the switch, if break is not added the program will continue execute the code in other cases even when the integer expression is not equal to that case.

This can be exploited in some cases as seen in the next example. We want to separate an input from digit to other characters.

Example:

char ch = cin.get() //get the character
switch (ch) {
case '0':
        // do nothing fall into case 1
case '1':
        // do nothing fall into case 2
case '2':
       // do nothing fall into case 3
...
case '8':
       // do nothing fall into case 9
case '9':
      cout << "Digit" << endl; //print into stream out
      break;
default:
      cout << "Non digit" << endl; //print into stream out
      break;
}

In this small piece of code for each digit below ‘9’ it will propagate through the cases until it will reach case ‘9’ and print “digit”.

break; can only break out of the innermost level. If for example you are inside a switch and need to break out of a enclosing for loop you might well consider adding a boolean as a flag, and check the flag after the switch block instead of the alternatives available.

continue is not relevant to switch block. Calling continue within a switch block will lead to the “continue” of the loop which wraps the switch block.

Related posts