1 <!DOCTYPE HTML PUBLIC
"-//W3O//DTD W3 HTML 2.0//EN">
2 <!-- This collection of hypertext pages is Copyright 1995, 1996 by Steve Summit. -->
3 <!-- This material may be freely redistributed and used -->
4 <!-- but may not be republished or sold without permission. -->
7 <link rev=
"owner" href=
"mailto:scs@eskimo.com">
8 <link rev=
"made" href=
"mailto:scs@eskimo.com">
9 <title>section
3.4: Switch
</title>
10 <link href=
"sx6c.html" rev=precedes
>
11 <link href=
"sx6e.html" rel=precedes
>
12 <link href=
"sx6.html" rev=subdocument
>
15 <H2>section
3.4: Switch
</H2>
18 <p>We won't be concentrating on
<TT>switch
</TT> statements much
19 (they're a bit of a luxury;
20 there's nothing you can do with a
<TT>switch
</TT>
21 that you can't do with an
<TT>if
</TT>/
<TT>else
</TT> chain,
22 as in section
3.3 on page
57).
23 But they're quite handy,
24 and good to know about.
25 </p><p>The example on page
59 is about as contrived as the example in
29 but studying both examples will give you an excellent feel for
30 how a
<TT>switch
</TT> statement works,
31 what the
<TT>if
</TT>/
<TT>then
</TT> statements are
32 that a
<TT>switch
</TT> is equivalent to
33 and how to map between the two,
34 and why a switch statement can be convenient.
37 note especially the way that ten
<TT>case
</TT> labels are
38 attached to one set of statements
39 (
<TT>ndigit[c-'
0']++;
</TT>).
40 As the authors point out,
41 this works because of the way switch cases ``fall through,''
42 which is a mixed blessing.
43 </p><p>The danger of fall-through is illustrated by:
57 </pre>When
<TT>food
</TT> is
<TT>APPLE
</TT>,
58 this code erroneously prints
61 </pre>because the
<TT>break
</TT> statement after the
<TT>APPLE
</TT> case was omitted.
65 <a href=
"sx6c.html" rev=precedes
>prev
</a>
66 <a href=
"sx6e.html" rel=precedes
>next
</a>
67 <a href=
"sx6.html" rev=subdocument
>up
</a>
68 <a href=
"top.html">top
</a>
71 This page by
<a href=
"http://www.eskimo.com/~scs/">Steve Summit
</a>
72 //
<a href=
"copyright.html">Copyright
</a> 1995,
1996
73 //
<a href=
"mailto:scs@eskimo.com">mail feedback
</a>