section 3.4: Switch

pages 58-59

We won't be concentrating on switch statements much (they're a bit of a luxury; there's nothing you can do with a switch that you can't do with an if/else chain, as in section 3.3 on page 57). But they're quite handy, and good to know about.

The example on page 59 is about as contrived as the example in section 1.6 (page 22) which it replaces, but studying both examples will give you an excellent feel for how a switch statement works, what the if/then statements are that a switch is equivalent to and how to map between the two, and why a switch statement can be convenient.

In the example in the text, note especially the way that ten case labels are attached to one set of statements (ndigit[c-'0']++;). As the authors point out, this works because of the way switch cases ``fall through,'' which is a mixed blessing.

The danger of fall-through is illustrated by:

	switch(food) {
		case APPLE:
			printf("apple\n");


case ORANGE: printf("orange\n"); break;

default: printf("other\n"); }
When food is APPLE, this code erroneously prints
	apple
	orange
because the break statement after the APPLE case was omitted.


Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995, 1996 // mail feedback