Chapter 7Switching PathsIn This Chapter▶ Using the switch keyword to choose between multiple paths▶ Taking a default path▶ Falling through from one case to anotherOften programs have to decide between a very limited number of options: Either m is greater than n or it’s not; either the lug nut is present or it’s not. Sometimes, however, a program has to decide between a largenumber of possible legal inputs. This could be handled by a series of ifstatements, each of which tests for one of the legal inputs. However, C++ provides a more convenient control mechanism for selecting among a number ofoptions known as the switch statement.Controlling Flow with
the switch StatementThe switch statement has the following format:switch(expression){
case const1:
// go here if expression == const1
break;
case const2:
// go here if expression == const2
break;
case const3: // repeat as often as you like
// go here if expression == const3
break;
default:
// go here if none of the other cases match
}
82 Part II: Writing a Program: Decisions, DecisionsUpon encountering the switch statement, C++ evaluates expression. Itthen passes control to the case with the same value as expression. Controlcontinues from there to the break statement. The break transfers control tothe } at the end of the switch statement. If none of the cases match, controlpasses to the default case.
The default case is optional. If the expression doesn’t match any case and no
default case is provided, control passes immediately to the }.Consider the following example code snippet:int nMonth;cout << “Enter the number of the month: “;
cin >> nMonth;
switch (nMonth)
{
case 1:
cout << “It’s January” << endl;
break;
case 2:
cout << “It’s February” << endl;;
break;
case 3:
cout << “It’s March” << endl;;
break;
case 4:
cout << “It’s April” << endl;;
break;
case 5:
cout << “It’s May” << endl;;
break;
case 6:
cout << “It’s June” << endl;;
break;
case 7:
cout << “It’s July” << endl;;
break;
case 8:
cout << “It’s August” << endl;;
break;
case 9:
cout << “It’s September”<< endl;;
break;
case 10:
cout << “It’s October” << endl;;
break;
case 11:
cout << “It’s November” << endl;;
break;
Chapter 7: Switching Paths 83case 12:cout << “It’s December” << endl;;
break;
default:
cout << “That’s not a valid month” << endl;;
}I got the following output from the program when inputting a value of 3:Enter the number of the month: 3It’s March
Press any key to continue . . .Figure 7-1 shows how control flowed through the switch statement to generate the earlier result of “March.”Figure 7-1:Flowthrough aswitchstatementlisting the
months of
the year
where the
operator
enters
month 3.int nMonth;cout << “Enter the number of the month: ”;
cin >> nMonth;
switch (nMonth)
{
case 1:
cout << “It’s January” << end1;;
break;
case 2:
cout << “It’s February” << end1;;
break;
case 3:
cout << “It’s March” << end1;;
break;
case 4:
cout << “It’s April” << end1;;
break;
case 5:
cout << “It’s January” << end1;
break;
case 12:
cout << “It’s December” << end1;;
break;
default:
cout << “That’s not a valid month” << end1;;
}For nMonth = 384 Part II: Writing a Program: Decisions, DecisionsA switch statement is not like a series of if statements. For example, onlyconstants are allowed after the case keyword (or expressions that can becompletely evaluated at build time). You cannot supply an expression after a
case. Thus, the following is not legal:// cases cannot be expressions; in general, the// following is not legal
switch(n)
{
case m:
cout << “n is equal to m” << endl;
break;
case 2 * m:
cout << “n is equal to 2m” << endl;
break;
case 3 * m:
cout << “n is equal to 3m” << endl;
}Each of the cases must have a value at build time. The value of m is notknown until the program executes.Control Fell Through: Did I break It?Just as the default case is optional, the break at the end of each case is alsooptional. Without the break statement, however, control simply continueson from one case to the next. Programmers say that control falls through.This is most useful when two or more cases are handled in the same way.
For example, C++ may differentiate between upper- and lowercase, but most
humans do not. The following code snippet prompts the user to enter a C to
create a checking account and an S to create a savings account. However, by
providing extra case statements, the snippet handles lowercase c and s the
same way:cout << “Enter C to create checking account, “<< “S to create a saving account, “
<< “and X to exit: “;
cin >> cAccountType;
switch(cAccountType)
{
case ‘S’: // upper case S
case ‘s’: // lower case s
// creating savings account
break;
case ‘C’: // upper case C
case ‘c’: // lower case c
Chapter 7: Switching Paths 85// create checking accountbreak;
case ‘X’: // upper case X
case ‘x’: // lower case x
// exit code goes here
break;
default:
cout << “I didn’t understand that” << endl;
}Implementing an Example Calculator
with the switch StatementThe following SwitchCalculator program uses the switch statement to implement a simple calculator:// SwitchCalculator - use the switch statement to// implement a calculator
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
// enter operand1 op operand2
int nOperand1;
int nOperand2;
char cOperator;
cout << “Enter ‘value1 op value2’\n”
<< “where op is +, -, *, / or %:” << endl;
cin >> nOperand1 >> cOperator >> nOperand2;
// echo what the operator entered
cout << nOperand1 << “ “
<< cOperator << “ “
<< nOperand2 << “ = “;
// now calculate the result; remember that the
// user might enter something unexpected
switch (cOperator)
{
86 Part II: Writing a Program: Decisions, Decisionscase ‘+’:cout << nOperand1 + nOperand2;
break;
case ‘-’:
cout << nOperand1 - nOperand2;
break;
case ‘*’:
case ‘x’:
case ‘X’:
cout << nOperand1 * nOperand2;
break;
case ‘/’:
cout << nOperand1 / nOperand2;
break;
case ‘%’:
cout << nOperand1 % nOperand2;
break;
default:
// didn’t understand the operator
cout << “ is not understood”;
}
cout << endl;
// wait until user is ready before terminating program
// to allow the user to see the program results
system(“PAUSE”);
return 0;
}This program begins by prompting the user to enter “value1 op value2”where op is one of the common arithmetic operators +, -, *, / or %. The program then reads the variables nOperand1, cOperator, and nOperand2.The program starts by echoing back to the user what it read from the keyboard. It follows this with the result of the calculation.
Echoing the input back to the user is always a good programming practice. It
gives the user confirmation that the program read his input correctly.
The switch on cOperator differentiates between the operations that thiscalculator implements. For example, in the case that cOperator is ‘+’, theprogram reports the sum of nOperand1 and nOperand2.Because ‘X’ is another common symbol for multiply, the program accepts‘*’, ‘X’, and ‘x’ all as synonyms for multiply using the case “fall through”feature. The program outputs an error message if cOperator doesn’t matchany of the known operators.
Chapter 7: Switching Paths 87The output from a few sample runs appears as follows:Enter ‘value1 op value2’where op is +, -, *, / or %:22 x 622 x 6 = 132Press any key to continue . . .
Enter ‘value1 op value2’
where op is +, -, *, / or %:22 / 622 / 6 = 3Press any key to continue . . .
Enter ‘value1 op value2’
where op is +, -, *, / or %:22 % 622 % 6 = 4Press any key to continue . . .
Enter ‘value1 op value2’
where op is +, -, *, / or %:22 $ 622 $ 6 = is not understoodPress any key to continue . . .Notice that the final run executes the default case of the switch statementsince the character ‘$’ did not match any of the cases.88 Part II: Writing a Program: Decisions, Decisions
No comments:
Post a Comment