Multiple Choice: switch and break

I l @ ve RuBoard

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 with that letter.\n");   printf("Please type in a letter; type # to end my act.\n");   while ((ch = getchar()) != `#')   {     if (islower(ch)) /* lowercase only */       switch (ch)       {         case `a' :               printf("argali, a wild sheep of Asia\n");               break;         case `b' :               printf("babirusa, a wild pig of Malay\n");               break;         case `c' :               printf("coati, racoonlike mammal\n");               break;         case `d' :               printf("desman, aquatic, molelike critter\n");               break;         case `e' :               printf("echidna, the spiny anteater\n");               break;         case `f' :               printf("fisher, brownish marten\n");               break;         default :               printf("That's a stumper!\n");       }  /* end of switch */     else       printf("I recognize only lowercase letters.\n");     while (getchar() != `\n')       continue;            /* skip rest of input line */     printf("Please type another letter or a #.\n");   }                        /* while loop end          */   printf("Bye!\n");   return 0; } 

We got a little lazy and stopped at f , but we could have continued in the same manner. Let's look at a sample run before explaining the program further.

 Give me a letter of the alphabet, and I will give an animal name beginning with that letter. Please type in a letter; type # to end my act.  a [enter]  argali, a wild sheep of Asia Please type another letter or a #.  dab [enter]  desman, aquatic, molelike critter Please type another letter or a #.  r [enter]  That's a stumper! Please type another letter or a #.  Q [enter]  I recognize only lowercase letters. Please type another letter or a #.  # [enter]  Bye! 

The program's two main features are its use of the switch statement and its handling of input. We'll look first at how switch works.

Using the switch Statement

The expression in the parentheses following the word switch is evaluated. In this case, it has whatever value you last entered for ch . Then the program scans the list of labels (here, case `a' :, case `b' : , and so on) until it finds one matching that value. The program then jumps to that line. What if there is no match? If there is a line labeled default : , the program jumps there. Otherwise, the program proceeds to the statement following the switch .

What about the break statement? It causes the program to break out of the switch and skip to the next statement after the switch (see Figure 7.5). Without the break statement, every statement from the matched label to the end of the switch would be processed . For example, if you removed all the break statements from the program and then ran the program using the letter d , you would get this exchange:

Figure 7.5. Program flow in switch es, with and without break s.
graphics/07fig05.jpg
 Give me a letter of the alphabet, and I will give an animal name beginning with that letter. Please type in a letter; type # to end my act.  d [enter]  desman, aquatic, molelike critter echidna, the spiny anteater fisher, a brownish marten That's a stumper! Please type another letter or a #.  # [enter]  Bye! 

All the statements from case `d' : to the end of the switch were executed.

Incidentally, a break statement works with loops and with switch , but continue works just with loops. However, continue can be used as part of a switch statement if the statement is in a loop. In that situation, as with other loops, continue causes the program to skip over the rest of the loop, including other parts of the switch .

If you are familiar with Pascal, you will recognize the switch statement as being similar to the Pascal case statement. The most important difference is that the switch statement requires the use of a break if you want only the labeled statement to be processed. Also, you can't use a range as a C case.

The switch test expression in the parentheses should be one with an integer value (including type char ). The case labels must be integer-type (including char ) constants or integer constant expressions (expressions containing only integer constants). You can't use a variable for a case label. This, then, is the structure of a switch :

 switch (  integer expression  )      {      case  constant1  :  statements  <--optional      case  constant2  :  statements  <--optional      default :    <--optional  statements  <--optional } 

Reading Only the First Character of a Line

The other new feature incorporated into animals.c is how it reads input. As you might have noticed in the sample run, when dab was entered, only the first character was processed. Often this behavior is desirable in interactive programs looking for single-character responses. The code responsible for this behavior is the following:

 while (getchar() != `\n')    continue;         /* skip rest of input line */ 

This loop reads characters from input up to and including the newline character generated by the Enter key. Note that the function return value is not assigned to ch , so the characters are merely read and discarded. Because the last character discarded is the newline character, the next character to be read is the first character of the next line. It gets read by getchar() and assigned to ch in the outer while loop.

If you omit this loop, the program runs into a bit of trouble. Suppose, for instance, you respond with the letter a . Entering a involves pressing the Enter key, so you actually send the sequence a followed by the newline character. After the program processes the a , it reads the newline character and prints "I recognize only lowercase letters." Therefore, each letter entered causes the program to run through the outer while loop twice, which is disconcerting to the user .

Another approach to the newline problem is to skip only newlines rather than the entire rest of the line. You can do that by using the following code as the first statement in the large while loop:

 if (ch == `\n')   continue; 

Multiple Labels

You can use multiple case labels for a given statement, as shown in Listing 7.12.

Listing 7.12 The vowels .c program.
 /* vowels.c -- uses multiple labels */ #include <stdio.h> int main(void) {   char ch;   int a_ct, e_ct, i_ct, o_ct, u_ct;   a_ct = e_ct = i_ct = o_ct = u_ct = 0;   printf("Enter some text; enter # to quit.\n");   while ((ch = getchar()) != `#')   {       switch (ch)       {         case `a' :         case `A' :  a_ct++;                     break;         case `e' :         case `E' :  e_ct++;                     break;         case `i' :         case `I' :  i_ct++;                     break;         case `o' :         case `O' :  o_ct++;                     break;         case `u' :         case `U' :  u_ct++;                     break;         default :   break;       }                                 /* end of switch  */   }                                     /* while loop end */   printf("number of vowels:   A    E    I    O    U\n");   printf("                 %4d %4d %4d %4d %4d\n",         a_ct, e_ct, i_ct, o_ct, u_ct);   return 0; } 

If ch is, say, the letter i , the switch statement goes to the location labeled case `i' : . Because there is no break associated with that label, program flow goes to the next statement, which is i_ct++; . If ch is I , program flow goes directly to that statement. In essence, both labels refer to the same statement.

Here's a sample run:

 Enter some text; enter # to quit.  I see under the overseer.#  number of vowels:   A    E    I    O    U                     0    7    1    1    1 

In this particular case, you can avoid multiple labels by using the toupper() function from the ctype.h family (refer to Table 7.2) to convert all letters to uppercase before testing:

 getchar()) != `#') {     ch = toupper(ch);     switch (ch)     {       case `A' :  a_ct++;                   break;       case `E' :  e_ct++;                   break;       case `I' :  i_ct++;                   break;       case `O' :  o_ct++;                   break;       case `U' :  u_ct++;                   break;       default :   break;     }                                 /* end of switch  */ }                   /* while loop end */ 

Or, if you want to leave ch unchanged, use the function this way:

 switch(toupper(ch)) 

Summary: Multiple Choice with switch

Keyword:

 switch 

General Comments:

Program control jumps to the case label bearing the value of expression . Program flow then proceeds through all the remaining statements unless redirected again with a break statement. Both expression and case labels must have integer values (type char is included), and the labels must be constants or expressions formed solely from constants. If no case label matches the expression value, control goes to the statement labeled default , if present. Otherwise, control passes to the next statement following the switch statement.

Form:

 switch (expression) { case label1 : statement1 /* use break to skip to end */     case label2 : statement2     default     : statement3 } 

There can be more than two labeled statements, and the default case is optional.

Example:

 switch (choice)     {     case 1 :     case 2 : printf("Darn tootin'!\n");  break;     case 3 : printf("Quite right!\n");     case 4 : printf("Good show!\n"); break;     default  : printf("Have a nice day.\n");     } 

If choice has the integer value 1 or 2 , the first message is printed. If it is 3 , the second and third messages are printed. (Flow continues to the following statement because there is no break statement after case 3 .) If it is 4 , the third message is printed. Other values print only the last message.

switch and if else

When should you use a switch and when should you use the if else construction? Often you don't have a choice. You can't use a switch if your choice is based on evaluating a float variable or expression. Nor can you conveniently use a switch if a variable must fall into a certain range. It is simple to write the following:

 if (integer < 1000 && integer > 2) 

Unhappily, covering this range with a switch would involve setting up case labels for each integer from 3 to 999. However, if you can use a switch , often your program runs a little faster and takes less code.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net