&&
The &&
operator also lets you set up a series of if else if else
statements, with each choice corresponding to a particular range of values. Listing 6.6 illustrates the approach. It also shows a useful technique for handling a series of messages. Just as a pointer-to-char
variable can identify a single string by pointing to its beginning, an array of pointers-to-char
can identify a series of strings. You simply assign the address of each string to a different array element. Listing 6.6 uses the qualify
array to hold the addresses of four strings. For example, qualify[1]
holds the address of the string "mud tug-of-war
"
. The program can then use qualify[1
] as it would any other pointer to a string—for example, with cout
or with strlen()
or strcmp()
. Using the const
qualifier protects these strings from accidental alterations.
// more_and.cpp -- using the logical AND operator
#include <iostream>
const char * qualify[4] = // an array of pointers
{ // to strings
"10,000-meter race.
",
"mud tug-of-war.
",
"masters canoe jousting.
",
"pie-throwing festival.
"
};
int main()
{
using namespace std;
int age;
cout << "Enter your age in years: ";
cin >> age;
int index;
if (age > 17 && age < 35)
index = 0;
else if (age >= 35 && age < 50)
index = 1;
else if (age >= 50 && age < 65)
index = 2;
else
index = 3;
cout << "You qualify for the " << qualify[index];
return 0;
}
Here is a sample run of the program in Listing 6.6:
Enter your age in years: 87
You qualify for the pie-throwing festival.
The entered age doesn’t match any of the test ranges, so the program sets index
to 3
and then prints the corresponding string.
In Listing 6.6, the expression age > 17 && age < 35
tests for ages between the two values—that is, ages in the range 18–34. The expression age >= 35 && age < 50
uses the >=
operator to include 35 in its range, which is 35–49. If the program used age > 35 && age < 50
, the value 35 would be missed by all the tests. When you use range tests, you should check that the ranges don’t have holes between them and that they don’t overlap. Also you need to be sure to set up each range correctly; see the sidebar “Range Tests,” later in this section.
The if else
statement serves to select an array index, which, in turn, identifies a particular string.
3.144.100.237