课程: Complete Guide to C Programming Foundations

Working with the switch-case structure

- [Instructor] This code shows a switch case structure, which is yet another way to alter program flow in C. This construction uses the C language keywords, switch, case, and default to form what's called a selection statement. You also see the break keyword associated with this structure. The switch case structure alters program flow like an if else, if else construction, but it behaves differently. Unlike if the switch statement doesn't evaluate a condition. Instead, it's followed by an expression that results in a single value, such as shown on line 10. Again, this isn't a comparison. What follows are a block of case statements enclosed in braces. Each case statement is followed by a literal or constant and a colon. This value is where the comparison is made. The switch value is compared with a literal or constant specified by the case statement. If a match is made, the statement's belonging to the case statement are executed, otherwise they're skipped, and the next case statement is evaluated. Program flow is altered by the break keyword which jumps execution down to the statement following the switch case structures block, the final curly bracket. In this code, the user is prompted to type values one, two, or three. The switch statement uses the value input, variable A, as its expression. When the value is one at line 12, the put statement executes and the break keyword exits the block. Otherwise execution falls through and the value is compared with two and then three. If nothing matches at this point, the default condition takes over, its statement is executed and the construction ends. Run the code. And I'll try first with one. And the first item, I'll run it again, and I'll do three, third item, and now I'll try a value that's out of range, say negative 16. Invalid choice. The break statements aren't a required part of the switch case construction, they're added so that execution doesn't continue to flow through the remaining statements. Comment out all the break statements to see what happens. Now let's see how the code runs. And I'll type one, and you see that all the put statements output their text. This switch case structure uses character variables to compare items input from a menu. All run, and all type, and a. Invalid choice. Hmm, I think you must type shift-a for capital A to make the match as shown here. But it would be nice if the code caught lowercase letters as well. So to improve it we can add some case statements. Lowercase a matches as well. You see that I've added lowercase case statements to match up their uppercase counterpart. Because execution falls through, both characters match input, upper and lowercase, generating the same result. This is one example of how fall-through between case statements can be useful. Run again, and now I can order my eyeball soup with a lowercase c, enjoy.

内容