Next: Exercises Up: Conditionals Previous: The ? operator

The switch statement

The C switch i allows multiple choice of a selection of items at one level of a conditional where it is a far neater way of writing multiple if statements:

switch (expression) {

In each case the value of itemi must be a constant, variables are not allowed.

The break is needed if you want to terminate the switch after execution of one choice. Otherwise the next case would get evaluated. Note: This is unlike most other languages.

We can also have null statements by just including a ; or let the switch statement fall through by omitting any statements (see e.g. below).

The default case is optional and catches any other cases.

For example:

switch (letter)

In the above example if the value of letter is 'A', 'E', 'I', 'O' or 'U' then numberofvowels is incremented.

If the value of letter is '' then numberofspaces is incremented.

If none of these is true then the default condition is executed, that is numberofconstants is incremented.


drago@scri.fsu.edu
Jan. 1997