You are here

C++ Code to Accomplish Multiway Selection

6 February, 2015 - 16:15

Using the same example as above, here is the C++ code to accomplish the case control structure.

Example 12.4: C++ source code -case structure with integers

switch (age)  {  case 18: cout _ "nnYou can vote.";           break;  case 39: cout _ "nnYou're middle aged.";           break;  case 65: cout _ "nnConsider retirement.";           break;  default: cout _ "nnAge is un-important.";}

The first thing you should note is that the C++ programming language does not formally have a case control structure. It does have a switch control structure but it acts differently than the traditional case control structure. We use a break (which is a branching control structure) with the switch to make it act like the traditional case structure. This is one of the few allowable ways to use the switch with break within the C++ programming language to simulate the traditional case structure. All other uses of the switch or break are to be avoided if you are to stay within the bounds of good structured programming techniques.

The value in the variable age is compared to the first "case" (note: case is one of the C++ reserved words) which is the value 18 (also called the listed value) using an equality comparison or is "age equal to 18". If it is true, the cout is executed which displays "You can vote." and the next line of code (the break) is done (which jumps us to the end of the control structure). If it is false, it moves on to the next case for comparison.

Most programming languages, including C++, require the listed values for the case control structure be of the integer family of data types. This basically means either an integer or character data type. Consider this example that uses character data type (choice is a character variable):

Example 12.5: C++ source code -case structure with characters

switch (choice)  {  case 'A': cout _ "nnYou are an A student.";            break;  case 'B': cout _ "nnYou are a B student.";            break;  case 'C': cout _ "nnYou are a C student.";            break;  default: cout _ "nnMaybe you should study harder.";  }