Switch Statements

Lessons

Credits for Lecturing and Authoring
Sample Problem
Switch Statements

Switch Statements

Authored by: John Even

Faculty Supervisor: Al Day

HTML Documentation by: Larry Genalo Jr.

Date Last Updated: 7/24/96

Sample Problem

Suppose you have given the user of your program a menu, asking them to input a letter from 'a' thru 'f' (capital or lowercase). You then print out the appropriate information depending on their selection. (Think of it as a primitive menu system)

       Choice               Screen Output
     'a' or 'A'             McDay's
     'b' or 'B'             Mickelson's Joint
     'c' or 'C'             Food Service
     'd' or 'D'             Genalo's Pizza

Hmm, so what would the menu code look like?

This is one possibility:


char choice;
    .
    .
if(choice=='A'||choice=='a'){
    printf("You had lunch at McDay's.\n");
} else if (choice=='B'||choice=='b') {
    printf("YES, Mickelson's Joint!\n");
} ...etc...

It gets the job done, but there must be some easier way of writing the code, right?

Of course there is, it is just a little more difficult to understand.

Switch Statements

Here is the same code in switch statement format

char choice;
switch (choice) {
case 'A': case 'a':
   printf("You had lunch at McDay's.\n");
   break;
case 'B': case 'b':
   printf("YES, Mickelson's Joint!\n");
   break;
case 'C': case 'c':
   printf("Nothin' says lovin' like a greasy pastry.\n");
   break;
case 'D': case 'd'"
   printf("How about them pizzas at Genalo's?!?\n");
   break:
default:
   printf("Fine, I guess fast food isn't good enough for you.\n");
}

As you can see, the switch statement code was a lot easier to type and read.

It works by taking the variable (choice) through the "cases" until a match is found. Statements following the matching case labels are executed until a break statement is encountered, then the switch statement is exited. If no matching case is found, the statements following the default label are executed, or the switch body is skipped entirely if no default statement is present.

Note: Switch statements may not be used with double and string variables -- only int and char will work.