C Tutorial (17) : Switch & Case

The if statement is great for simple testing of data, especially if your data tests have only two or three possibilities. You can use if to test for more than two values, but if you do, you have to nest several if statements inside one another, and that can get confusing and hard to maintain.

Consider for a moment how you execute code based on a user’s response to a menu. A menu is a list of options from which to select, such as this one:

What do you want to do?

1. Add New Contact
2. Edit Existing Contact
3. Call Contact
4. Text Contact
5. Delete Contact
6. Quit the Program 

What is your choice?

Note : When you create menus that ask for user input, you are creating a user interface.

It would take five if-else statements, nested inside one another, to handle all these conditions, as you can see here:

if (userAns == 1)
{
// Perform the Add Contact Routine
}
else if (userAns == 2)
{
//Perform the Edit Contact Routine
}
else if (userAns == 3)
{
//Perform the Call Contact Routine
}
else if (userAns == 4)
{
//Perform the Text Contact Routine
}
else if (userAns == 5)
{
//Perform the Delete Contact Routine
}
else
{
//Perform the Quit Routine
}

Nothing is wrong with nested if statements, but the C switch statement is clearer for multiple conditions.

SWITCH

The switch statement has one of the longest formats of any statement in C (or just about any other language). Here is the format of switch:

switch (expression)
{
case (expression1): 
   { one or more C statements; } 
case (expression2): 
   { one or more C statements; } 
case (expression3): 
   { one or more C statements; }

// This would keep going for however many case statements to test 
default: 
  { one or more C statements; }

Tip : As with most statements, the actual use of switch is a lot less intimidating than its format leads you to believe.

The following simple program uses a switch statement to print an appropriate message, depending on the choice the user makes.

/* This program presents a menu of choices, gets the user's choice, 
   and then uses the switch statement to execute a line or two of code 
   based on that choice. (What the user wants to do is not truly 
   implemented—it is just a series of stubs to teach the value of 
   the switch statement. */

#include <stdio.h>
#include <stdlib.h>

main()
{
int choice;
printf("What do you want to do?\n"); 
printf("1. Add New Contact\n"); 
printf("2. Edit Existing Contact\n");
printf("3. Call Contact\n"); 
printf("4. Text Contact\n"); 
printf("5. Exit\n");

do
{
printf("Enter your choice: "); 
scanf(" %d", &choice);

switch (choice)
{
case (1): 
printf("\nTo add you will need the ); 
printf("contact's\n");
printf("First name, last name, and number.\n"); 
break;

case (2): 
printf("\nGet ready to enter the name of "); 
printf("name of the\n");
printf("contact you wish to change.\n"); 
break;

case (3): 
printf("\nWhich contact do you "); 
printf("wish to call?\n");
break;

case (4): 
printf("\nWhich contact do you "); 
printf("wish to text?\n");
break;

case (5): 
exit(1); //Exits the program early

default:              
printf("\n%d is not a valid choice.\n", choice); 
printf("Try again.\n");
break;
}

} while ((choice < 1) || (choice > 5));// To continue till user enter valid input

return 0;
}

The case statements determine courses of action based on the value of choice.

Note : Anytime you need to terminate a program before its natural conclusion, use the exit() function. The value you place in the exit() parentheses is returned to your operating system. Most beginning programmers ignore the return value and put either a 0 or a 1 in the parentheses. You must remember to add with the #include directive in every program that uses exit().

If the user enters something other than a number from 1 to 5, the …is not a valid choice. message prints, thanks to the default keyword. C ensures that if none of the other cases matches the variable listed after switch, the default statements execute.

default works like else, in a way. else takes care of an action if an if test is false, and default takes care of an action if none of the other case conditions successfully matches the switch variable. Although default is optional (as is else), it’s good programming practice to use a default to handle unexpected switch values.

Note : The switch variable can be either an integer or a character variable. Do not use a float or a double for the switch test.

break and switch

The switch statement shown earlier has several break statements scattered throughout the code. The break statements ensure that only one case executes. Without the break statements, the switch would “fall through” to the other case statements. Here is what would happen if the break statements were removed from the switch and the user answered with a choice of 2:

Get ready to enter the name of the contact you wish to change.
Which contact do you wish to call? 
Which contact do you wish to text?

The break keeps switch case statements away from running together.

Note : The only reason the default condition’s message did not print is that the exit() function executed inside case (5).

Efficiency Considerations

case statements don’t have to be arranged in any order. Even default doesn’t have to be the last case statement. As a matter of fact, the break after the default statement isn’t needed as long as default appears at the end of switch. However, putting break after default helps ensure that you move both statements if you ever rearrange the case statements. If you were to put default higher in the order of case statements, default would require a break so that the rest of the case statements wouldn’t execute.

Tip : You can rearrange the case statements for efficiency. Put the most common case possibilities toward the top of the switch statement so that C doesn’t have to search down into the case statements to find a matching case.

Well, although you can nest if statements in other if statements and nest for statements within other for statements, nesting switch statements is not a good idea, particularly when the default choices start overlapping. It confuses your compiler, and the program will not run.

Another note is that, open and closing braces for the statements after each case (expression): statement. The braces are not needed, but with more complex blocks of code, the braces can help keep things clear.

Break & Continue < Prev                       Next > getch, putch, getchar & putchar

Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s