C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

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.

Let’s add a second program to demonstrate the switch statement, as well as a program that uses two
levels of menus.


Click here to view code image


// Example program #2 from Chapter 17 of Absolute Beginner's Guide to
// C, 3rd Edition
// File Chapter17ex2.c
/* This program presents a menu of choices (three different decades), gets the user's
choice, and then presents a secondary menu (sports, entertainment, and politics).
When the user makes her second choice, it prints a list of key information from that
specific decade in that specific category. */

#include <stdio.h>
#include <stdlib.h> //Remember, if you plan to use exit(), you need
// this header file
main()
{
// Despite being a long program, you only need two variables:
// one for the first menu and one for the second
int choice1;
int choice2;

// The potential decade choices
printf("What do you want to see?\n");
printf("1. The 1980's\n");
printf("2. The 1990's\n");
printf("3. The 2000's\n");
Free download pdf