A Multitude of Options

It is not uncommon for us to need to select among several options instead of just a two-way decision. Such a decision might look like:

[Two-way branch flow chart]

Doing it with if

One way to implement such a structure is to use a series of if - else statements like this:
if(option == 1)
   ...
else if(option == 2)
   ...
else if(option == 3)
   ...
   .
   .
   .
else
   ...

and there do exist circumstances where we don't have any choice but to do it this way.

Notice that even though the later if statements are in the else clause of the first if statement, we don't indent these false branches. Instead we think of the else if as an idiom that is like its own keyword. Thus we recognize this structure as a multi-way decision.

The switch Statement

Probably the most common cases of multi-way decisions are among values for integer expressions or for character expressions. (In identifying these two cases, we are excluding the cases where we're making the decision on a floating point value and on a string of characters (like a word).) For this common case, C provides a statement whose keyword is switch . If we write the example above using the switch it would look like:
switch(optio ) {
case 1:
   ...
   break ;
case 2:
   ...
   break;
case 3:
   ...
   break;
    .
    .
    .
default:
   ...
   break;
}

Similarly, if option were a character instead of an integer, we could us the switch like this:
switch(option) {
case 'a':
case 'A':
   ...
   break;
case 'b':
case 'B':
   ...
   break;
case 'c':
case 'C':
   ...
   break;
    .
    .
    .
default:
   ...
   break;
}

Notice that when we have a constant character, we put it in single quotes to distinguish it from a variable by the same name. Also notice that we can have multiple case labels on the same selection. Here it means that if the character was an 'a' or an 'A' (that is a lower or uppercase a), then we'll do that first block of code.

The break statement

There's another feature of the switch that we haven't seen before, the break statement. In the context of a switch , it transfers control to the bottom of the switch statement. (We'll see later that it does the same thing with looping statements.)

Without the break statement, flow would "fall through" into the next case. For example, if a = 5


switch(a) {
case 5:
   x = y;
case 6:
   x = z ;
   break;
}

x will end up being equal to z just as if a had been 6.
What is the value of x at the end of this switch statement?
x = 10;
switch(x) {
case 1:
case 2:
   x++;
   break;
case 8:
case 9:
case 10:
case 11:
   x--;
case 13:
   x *= 2;
   break;
default:
   x = 0;
}

10

11

9

18

0