The switch construction is another way of making decisions in C
code. It is very flexible, but only tests for integer and character
values. It has the following general form:
switch (integer or character expression)
{
case constant1 : statement1;
break; /* optional */
case constant2 : statement2;
break; /* optional */
case constant3 : statement3;
break; /* optional */
...
}
The integer or character expression in the parentheses is evaluated, and
the program checks whether it matches one of the constants in the
various cases listed. If there is a match, the statement following
that case will be executed, and execution will continue until either a
break statement or the closing curly bracket of the entire
switch statement is encountered.
One of the cases is called default. Statements after the
default case are executed when none of the other cases are
satisfied. You only need a default case if you are not sure you are
covering every case with the ones you list.
Here is an example program that uses the switch statement to
translate decimal digits into Morse code: