Chapter 7

Switching Paths

In This Chapter

arrow Using the switch keyword to choose among multiple paths

arrow Taking a default path

arrow Falling through from one case to another

Often programs have to decide between two 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 on one option out of a large number of possible legal inputs. This situation could be handled by a series of if statements, each of which tests for one of the legal inputs. However, C++ provides a more convenient control mechanism for selecting among multiple options: the switch statement. This chapter gives you a closer look at what the switch statement is, what it does, and how to use it.

Controlling Flow with the switch Statement

The 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
}

Upon encountering the switch statement, C++ evaluates expression. It then passes control to the case with the same value as expression. Control continues from there to the break statement, which transfers control to the } at the end of the switch statement. If none of the cases match, control passes 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;
  case 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: 3
It's March
Press Enter to continue …

Figure 7-1 shows how control flowed through the switch statement to generate the earlier result of March.

9781118823873-fg0701.tif

Figure 7-1: Flow through a switch statement listing the months of the year where the operator enters month 3.

warning.eps A switch statement is not like a series of if statements. For example, only constant integers or characters are allowed after the case keyword (that is expressions that can be completely evaluated at build time). You cannot supply an run time expression after a case. Thus the following is not legal:

  // cases cannot be expressions; the
// following is not legal for m declared as an int
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 not known until the program executes.

technicalstuff.eps Actually, the 2011 C++ standard introduces a constant expression type that can be used as the target of a case statement, but that’s a bit beyond the scope of this book.

Control Fell Through: Did I break It?

Just as the default case is optional, so the break at the end of each case is also optional. Without the break statement, however, control simply continues to move from one case to the next. Programmers say that control falls through. Falling through is most useful when two or more cases are handled in the same way.

For example, C++ may differentiate between upper- and lowercase characters in code, but most humans don’t. The following code snippet prompts the user to enter a C to create a checking account and an S to create a savings account. The user might enter a capital or lowercase letter. To keep C++ happy, the following snippet provides extra case statements to handle lowercase c and s:

  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
    // create checking account
    break;

  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 Statement

The 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' "
         << "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)
    {
        case '+':
            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
    cout << "Press Enter to continue..." << endl;
    cin.ignore(10, ' '),
    cin.get();
    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.

tip.eps 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 this calculator implements. For example, in the case that cOperator is '+', the program 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 match any of the known operators.

The output from a few sample runs appears as follows:

  Enter 'value1 op value2'
where op is +, -, *, / or %:
22 x 6
22 x 6 = 132
Press Enter to continue …

  Enter 'value1 op value2'
where op is +, -, *, / or %:
22 / 6
22 / 6 = 3
Press Enter to continue …

  Enter 'value1 op value2'
where op is +, -, *, / or %:
22 % 6
22 % 6 = 4
Press Enter to continue …

  Enter 'value1 op value2'
where op is +, -, *, / or %:
22 $ 6
22 $ 6 =  is not understood
Press Enter to continue …

Notice that the final run executes the default case of the switch statement since the character '$' did not match any of the cases.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.240.252