* remove "\r" nonsense
[mascara-docs.git] / C / the.ansi.c.programming.language / notes.accompany.ansi.c / sx6d.html
blob5682bc44594673dc29f775a0d97c2f1f7888f54f
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. -->
5 <html>
6 <head>
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>
13 </head>
14 <body>
15 <H2>section 3.4: Switch</H2>
17 pages 58-59
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
26 section 1.6
27 (page 22)
28 which it replaces,
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.
35 </p><p>In the example
36 in the text,
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:
44 <pre> switch(food) {
45 case APPLE:
46 printf("apple\n");
47 <br>
48 <br>
49 case ORANGE:
50 printf("orange\n");
51 break;
52 <br>
53 <br>
54 default:
55 printf("other\n");
57 </pre>When <TT>food</TT> is <TT>APPLE</TT>,
58 this code erroneously prints
59 <pre> apple
60 orange
61 </pre>because the <TT>break</TT> statement after the <TT>APPLE</TT> case was omitted.
62 </p><hr>
63 <p>
64 Read sequentially:
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>
69 </p>
70 <p>
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>
74 </p>
75 </body>
76 </html>