Next: Exercises Up: Conditionals Previous: The ? operator

The switch statement

The C switch is similar to Pascal's case statement and it 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:

In each case the value of item 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:-

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.
Wed Sep 14 10:06:31 BST 1994