The switch Statement

Often in C programs (especially when writing "predicate" functions or functions to do conversions), we end up writing a sequence of code that looks like:
     if( <expression> == <constant1> ) <do_something>
     else if( <expression> == <constant2> ) <do_something_else>
     else if( <expression> == <constant3> ) <do_yet_another_thing>
     ...
     else <do_the_last_resort>

Because this is so common, the language provides a short hand way of saying the same thing more efficiently (it also executes more effciently). The control construct to do this is called the switch statement.

The above code sequence can be written as:

     switch(<expression>)
     {  case <constant1>: <do_something>
                          break;
        case <constant2>: <do_something_else>
                          break;
        case <constant3>: <do_yet_another_thing>
                          break;
        ...
        default :         <do_the_last_resort>
     }

This statement executes by evaluating the <expression > just once, and searching the case labels in the body of the switch to find the <constant > that matches the value of the <expression > and then executing the statement(s) beginning at that label. If none match, it would begin executing at the default by <do_the_last_resort > . In this case, those break statements are required to get the same effect of the nested if statements we had above.

When the break statement occurring in the compound statement in a switch (or while) is executed, it causes the compound statement to terminate immediately.

For example, if the <expression > evaluated to a value that matched <constant2 > the switch would begin with <do_something_else >, and then execute the break, ending the switch statement.

If on the other hand, we left the breaks out:

     switch(<expression>)
     {  case <constant1>: <do_something>

        case <constant2>: <do_something_else>

        case <constant3>: <do_yet_another_thing>

        ...
        default :         <do_the_last_resort>
     }

and the <expression > evaluated to a value that matched <constant2 > the switch would begin with <do_something_else >, and then <do_yet_another_thing > and any others up to the <do_the_last_resort > . However, sometimes that is exactly what we want to do:
     switch(<expression>)
     {  case <constant1>:

        case <constant2>:

        ...
        case <constantn>: <do_something>
                          break;

        default :         <do_the_last_resort>
     }

which will <do_something > if the <expression > matches any of the constants, and <do_the_last_resort > otherwise.

General switch syntax

We can use the switch statement in some of the roman utility functions.
[up] to Overview.