Multiple Choice: switch and break
The conditional operator and the if else construction make it easy to write programs that choose between two alternatives. Sometimes, however, a program needs to choose one of several alternatives. You can do this by using if else if…else, but in many cases it is more convenient to use the C switch statement. Listing 7.11 is an example showing how the switch statement works. This program reads in a letter and then responds by printing an animal name that begins with that letter.
Listing 7.11 The animals.c program.
/* animals.c -- uses a switch statement */ #include <stdio.h> #include <ctype.h> int main(void) { char ch; printf("Give me a letter of the alphabet, and I will give "); printf("an animal name\nbeginning ... |
Get C Primer Plus®, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.