Now let’s consider the || (logical OR) operator. Suppose we wish to ensure that either or both of two conditions are true
before we choose a certain path of execution. In this case, we use the ||
operator, as in the following program segment:
if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 ) )
cout << "Student grade is A" << endl;
which contains two simple conditions. The simple condition semesterAverage >= 90
evaluates to determine whether the student deserves an “A” in the course because of a solid performance throughout the semester. The simple condition finalExam >= 90
evaluates to determine whether the student deserves an “A” in the course because of an outstanding performance on the final exam. The if
statement then considers the combined condition
( semesterAverage >= 90 ) || ( finalExam >= 90 )
and awards the student an “A” if either or both of the simple conditions are true
. The message “Student grade is A
” prints unless both of the simple conditions are false
. Figure 5.16 is a truth table for the logical OR operator (||
).
The &&
operator has a higher precedence than the ||
operator. Both operators associate from left to right. An expression containing &&
or ||
operators evaluates only until the truth or falsehood of the expression is known. Thus, evaluation of the expression
( gender == FEMALE ) && ( age >= 65 )
stops immediately if gender
is not equal to FEMALE
(i.e., the entire expression is false
) and continues if gender
is equal to FEMALE
(i.e., the entire expression could still be true
if the condition age >= 65
is true
). This performance feature for the evaluation of logical AND and logical OR expressions is called short-circuit evaluation.
Performance Tip 5.3
In expressions using operator &&, if the separate conditions are independent of one another, make the condition most likely to be false the leftmost condition. In expressions using operator ||
, make the condition most likely to be true the leftmost condition. This use of short-circuit evaluation can reduce a program’s execution time.