5.3 Switch

When you have to make a decision by checking a variable that can have more that two values, you can use nested ifs, one for each value. C provides a more efficient way to perform this task: the switch construct.

It's syntax is:

    switch (selector) {
    case value1:
        statement;
        break;
    case value2:
        statement;
        break;
      /* ... */
    case valueN:
        statement;
        break;
    default:
        statement;
        break;
    }


The switch construct works this way: the selector is matched against each value specified by the case word, and when a match occurs the corresponding statement is executed. If no match is found the optional default statement, if presents, is executed. If no default case is provided and no match is found than nothing inside the switch is executed.

Note: The ``selector'' must be a simple C type, typically integer based type. In particular it cannot be a string value since, as discussed in XXX, strings in C are really arrays of characters.

This, and other documents, can be downloaded from http://opencbp.sourceforge.net/.

For questions about the Open C Book Project, read the documentation.