Using the switch Statement with Logical Operators


Using the switch Statement with  Logical  Operators

The switch statement was discussed at some length in Chapter 5. However, so far in this chapter it has been conspicuous by its absence.

In Chapter 5, we discussed how the switch statement was cumbersome when dealing with a range of numbers. The reason was that the case keyword cannot be followed by a range of numbers because it must instead be followed by a single integer constant.

However, the switch statement may be used with expressions that use the logical And or Or operator. The reason is that these expressions have only one of two possible values, true or false. True and false are both constants; the value of true is always true and the value of false is always false. While true and false are Boolean values, each has a corresponding integer value: 1 and 0. Therefore, the case keyword may be followed by true or false, just as in Chapter 5 where the case keyword can be followed by a character since a character has a corresponding integer ANSI or ASCII value.

For example, earlier in this chapter the logical And operator was used in the following if/else structure in determining whether the user is eligible to vote, the criteria being that the user must be at least 18 years old and a citizen.

 if (age >= 18 && citizen == true)  cout << "You are eligible to vote";  else  cout << "You are not eligible to vote"; 

The corresponding switch statement is

 switch (age >= 18 && citizen == true)  {  case true:  cout << "You are eligible to vote";  break;  case false:  cout << "You are not eligible to vote"; } 

Also earlier in this chapter, the logical Or operator was used in the following if/else structure in determining whether the user gets into a movie free, the criteria being that the user must be either under 18 or at least 65 years old.

 if (age <= 12  age >= 65)  cout << "Admission is free";  else  cout << "You have to pay"; 

The corresponding switch statement is

 switch (age <= 12  age >= 65) {  case true:  cout << "Admission is free";  break;  case false:  cout << "You have to pay"; } 

These examples illustrate that the switch statement can be employed as an alternative to an if / else or if / else if /else structure in programs that evaluate Boolean expressions using logical operators. However, it is not common for the switch statement to be employed in this manner because, with Boolean expressions, there are always just two alternatives, true and false, and switch statements generally are used when there are many more alternatives than two.




C++ Demystified(c) A Self-Teaching Guide
C++ Demystified(c) A Self-Teaching Guide
ISBN: 72253703
EAN: N/A
Year: 2006
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net