Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C For Dummies 2nd Ed 2004.pdf
Скачиваний:
43
Добавлен:
17.08.2013
Размер:
8.34 Mб
Скачать

Chapter 19: Switch Case, or, From ‘C’ to Shining ‘c’ 243

You’re changing all the if statements into a switch-case thing. Be careful what you type. When you’re done, double-check Lines 19 through 37 in the source code to make sure that you got it right. (The first few lines of the pro­ gram don’t change.)

Compile. Fix any errors or typos. Note that those are colons — not semicolons — on the case lines. The character constants are enclosed in single quotes. The word default also ends in a colon.

Run. You should see no difference in the output. Internally, however, you have converted an ugly string of if-else statements into an elegant decisionmaking structure: the switch-case loop (or “structure thing”).

Detailed information on what happens in a switch-case loop is covered in the next section.

The switch command in Line 19 takes the single character typed at the keyboard (from Line 18) and tells the various case statements in its curly braces to find a match.

Each of the case statements (Lines 21, 24, 27, and 30) compares its char­ acter constant with the value of variable c. If there’s a match, the state­ ments belonging to that case are executed.

The break in each case statement tells the compiler that the switchcase thing is done and to skip the rest of the statements.

If the break is missing, execution falls through to the next group of case statements, which are then executed, no matter what. Watch out for that! Missing breaks are the bane of switch-case loops.

The final item in the switch-case thing is default. It’s the option that gets executed if no match occurs.

The Old switch-case Trick

This is one booger of a command to try to become comfy with. Although switch-case things are important, they contain lots of programming finesse that many beginners stumble over. My advice is to work through the programs in this chapter to get a feel for things and then check mark bullets in this section for review purposes or to figure out what went wrong when things don’t work.

The switch keyword is used to give your programs an easy way to make multiple-choice guesses. It should replace any long repetition of if-else statements you’re using to make a series of comparisons.

244 Part III: Giving Your Programs the Ability to Run Amok

Using switch involves creating a complex structure that includes the case, break, and default keywords. Here’s how it may look:

switch(choice)

{

case item1:

statement(s); break;

case item2:

case item3:

statement(s); break;

default:

statement(s);

}

choice must be a variable. It can be a key typed at the keyboard, a value returned from the mouse or joystick, or some other interesting number or character the program has to evaluate.

After the case keyword come various items; item1, item2, item3, and so on are the various items that choice can be. Each one is a constant, either a char­ acter or a value; they cannot be variables. The case line ends in a colon, not in a semicolon.

Belonging to each case item are one or more statements. The program exe­ cutes these statements when item matches the choice that switch is making — like an if statement match. The statements are not enclosed in curly braces. The statements are also optional. (More on that in a second.)

The last statement in a group of case statements is typically a break com­ mand. Without the break there, the program keeps working its way through the next case statement.

The last item in the switch structure is default. It contains the statements to be executed when no match occurs — like the final else in an if-else structure. The default statements are executed no matter what (unless you break out of the structure earlier).

The most important thing to remember about switch-case is that the pro­ gram always walks through the entire thing unless you put a break in there when you want it to stop. For example, consider this program snippet:

switch(key)

{

case ‘A’:

printf(“The A key.\n”); break;

Chapter 19: Switch Case, or, From ‘C’ to Shining ‘c’ 245

case ‘B’:

printf(“The B key.\n”); break;

case ‘C’: case ‘D’:

printf(“The C or D keys.\n”); break;

default:

printf(“I don’t know that key.\n”);

}

Suppose that key is a single-character variable containing a character that was just typed at the keyboard. Here are three examples of how it would work:

Example 1: Suppose that the key variable contains the letter A. The program works:

switch(key)

Pick a key! So, key equals big A. Mosey on down the case list:

case ‘A’:

Yup, we have a match. The value of key equals the constant, big A. Execute those statements:

printf(“The A key.\n”);

Message printed. Then:

break;

Bail out of the switch-case thing. I’m done.

If you didn’t bail out at this point, the rest of the statements in the switchcase structure would be executed no matter what.

Example 2: Suppose that a user presses the C key. Here’s how it works:

switch(key)

key is a C. It’s time to check the case statements for a match:

case ‘A’:

246 Part III: Giving Your Programs the Ability to Run Amok

Nope! Skip to the next case:

case ‘B’:

Nope! Skip to the next case:

case ‘C’:

Yup! There’s a match. The value of key equals the character constant ‘C’ right here. What’s next?

case ‘D’:

The computer just goes ho-hum. There’s no match, but it’s still waiting for instructions because it matched the case ‘C’. Because the statements after case ‘D’ are the first that it finds, it executes those:

printf(“The C or D keys.\n”);

Message printed. Then:

break;

The rest of the switch-case structure is skipped.

Example 3: This time, the character X is entered at the keyboard. Here’s how the switch-case thing works:

switch(key)

key is an X. The computer wends its way through the case statements for a match:

case ‘A’:

Nope! Skip to the next case:

case ‘B’:

Nope! Skip to the next case:

case ‘C’:

Nope! Skip to the next case:

case ‘D’:

Chapter 19: Switch Case, or, From ‘C’ to Shining ‘c’ 247

Nope! All the cases are done. What’s left is the default, which supposedly handles everything else — including the X:

default:

and the only statement:

printf(“I don’t know that key.\n”);

The switch-case structure is done.

The thing in switch’s parentheses (choice) must work out to either a character value or an integer value. Most programmers put a character or integer variable there. You can also put a C language statement or function in the parentheses, as long as it works out to a character value or an integer value when it’s done.

The case line ends with a colon, not a semicolon. The statements belonging to case aren’t enclosed in curly braces.

The last statement belonging to a group of case statements is usually break. This statement tells the computer to skip over the rest of the switch structure and keep running the program.

If you forget the break, the rest of the switch structure keeps running. That may not be what you want.

The computer matches each item in the case statement with the choice that switch is making. If there’s a match, the statements belonging to that case are executed; otherwise, they’re skipped.

It’s possible for a case to lack any statements. In that case, a match simply “falls through” to the next case statement.

The keyword case must be followed by a constant value — either a number or a character. For example:

case 56: /* item 56 chosen */

or

case ‘L’:

/* L key pressed */

You cannot stick a variable there. It just doesn’t work. You may want to. You may even e-mail me, asking whether you can, but you can’t. Give up now.

Most C manuals refer to the command as switch, and case is just another keyword. I use switch-case as a unit because it helps me remember that the second word is case and not something else.

You don’t need a default to end the structure. If you leave it off and none of the case’s items matches, nothing happens.