||
In English, the word or can indicate when one or both of two conditions satisfy a requirement. For example, you can go to the MegaMicro company picnic if you or your spouse work for MegaMicro, Inc. The C++ equivalent is the logical OR operator, written ||
. This operator combines two expressions into one. If either or both of the original expressions is true
, or nonzero, the resulting expression has the value true
. Otherwise, the expression has the value false
. Here are some examples:
5 == 5 || 5 == 9 // true because first expression is true
5 > 3 || 5 > 10 // true because first expression is true
5 > 8 || 5 < 10 // true because second expression is true
5 < 8 || 5 > 2 // true because both expressions are true
5 > 8 || 5 < 2 // false because both expressions are false
Because the ||
has a lower precedence than the relational operators, you don’t need to use parentheses in these expressions. Table 6.1 summarizes how the ||
operator works.
C++ provides that the ||
operator is a sequence point. That is, any value changes indicated on the left side take place before the right side is evaluated. (Or in the newer parlance of C++11, the subexpression to the left of the operator is sequenced before the subexpression to the right.) For example, consider the following expression:
i++ < 6 || i == j
Suppose i
originally has the value 10
. By the time the comparison with j
takes place, i
has the value 11
. Also C++ won’t bother evaluating the expression on the right if the expression on the left is true, for it only takes one true expression to make the whole logical expression true. (The semicolon and the comma operator, recall, are also sequence points.)
Listing 6.4 uses the ||
operator in an if
statement to check for both uppercase and lowercase versions of a character. Also it uses C++’s string concatenation feature (see Chapter 4, “Compound Types”) to spread a single string over three lines.
// or.cpp -- using the logical OR operator
#include <iostream>
int main()
{
using namespace std;
cout << "This program may reformat your hard disk
"
"and destroy all your data.
"
"Do you wish to continue? <y/n> ";
char ch;
cin >> ch;
if (ch == 'y' || ch == 'Y') // y or Y
cout << "You were warned!aa
";
else if (ch == 'n' || ch == 'N') // n or N
cout << "A wise choice ... bye
";
else
cout << "That wasn't a y or n! Apparently you "
"can't follow
instructions, so "
"I'll trash your disk anyway.aaa
";
return 0;
}
(The program doesn’t really carry out any threats.) Here is a sample run of the program in Listing 6.4:
This program may reformat your hard disk
and destroy all your data.
Do you wish to continue? <y/n> N
A wise choice ... bye
The program reads just one character, so only the first character in the response matters. That means the user could have input NO!
instead of N
. The program would just read the N
. But if the program tried to read more input later, it would start at the O
.
3.137.216.175