switch (expression){
case constant-expression: zero-or-more-statements
default: zero-or-more-statements
case constant-expression: zero-or-more-statements
}
Each case is introduced by triplets of the keyword case, followed by an integer-valued constant or
constant expression, followed by a colon. Execution starts at the case that matches the expression. The
default case (if present) can appear anywhere in the list of cases, and will be executed if none of the
cases match. If there's no default case and none of the cases match, nothing is done by this statement.
Some people have suggested that it might be better to have a runtime error for the "no match" case, as
does Pascal. Runtime error checking is almost unknown in C—checking for dereferencing an invalid
pointer is about the only case, and even that limited case can't be fully done under MS-DOS.
Handy Heuristic
Runtime Checking in MS-DOS
Invalid pointers can be the bane of a programmer's life. It's just too easy to reference
memory using an invalid pointer. All virtual memory architectures will fault a process that
dereferences a pointer outside its address space as soon as this happens. But MS-DOS
doesn't support virtual memory, so it cannot catch the general case at the instant of failure.
However, MS-DOS can and does use a heuristic to check the specific case of dereferencing
a null pointer, after your program has finished. Both Microsoft and Borland C, before
entering your program, save the contents of location zero. As part of their exit code, they
check whether it now contains a different value. If it does, it's a pretty fair bet that your
program stored through a null pointer, and the runtime system prints the warning "null
pointer assignment".
More about this in Chapter 7.
Runtime checking goes against the C philosophy that the programmer knows what he or she is doing
and is always right.
The cases and the default can come in any order, though by convention the default case is usually the
last one. A conformant C compiler must permit at least 257 case labels for a switch statement (ANSI
C Standard, section 5.2.4.1). This is to allow a switch on an 8-bit character (256 possible values, plus
EOF).
Switch has several problems, one of which is that it is too relaxed about what it accepts in the cases.
For example, you can declare some local storage by following the switch's opening curly brace with a
declaration. This is an artifact of the original compiler—most of the same code that processed any