Selecting

If you want to test to see if a variable is one of several values, using multiple if statements becomes cumbersome. The C++ switch statement fulfills this purpose much better. The basic syntax is shown here:

    int i;     std::cin >> i;     switch(i)     {         case 1:              std::cout << "one" << std::endl;             break;         case 2:              std::cout << "two" << std::endl;             break;         default:             std::cout << "other" << std::endl;     }

Each case is essentially a label as to the specific code to be run if the selected variable is the specified value. The default clause is for values where there exists no case. You do not have to have a default clause, which means that you are testing only for specified cases. The default clause could be for the most common case (in which ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.