|
|
|
|
|
|
|
Caution: It's easy to confuse the assignment operator (=) and the == relational operator. These two operators have very different effects in a program. Some people pronounce the relational operator as equals-equals to remind themselves of the difference. |
|
|
|
|
|
|
|
|
In mathematics, the logical operators AND, OR, and NOT take logical expressions as operands. C++ uses special symbols for the logical operators: && (for AND), || (for OR), and ! (for NOT). By combining relational operators with logical operators, we can make more complex assertions. For example, suppose we want to determine whether a final score is greater than 90 and a midterm score is greater than 70. In C++, we would write the expression this way: |
|
|
|
|
|
|
|
|
finalScore > 90 && midtermScore > 70 |
|
|
|
|
|
|
|
|
The AND operation (&&) requires both relationships to be TRUE in order for the overall result to be TRUE. If either or both of the relationships are FALSE, the entire result is FALSE. |
|
|
|
|
|
|
|
|
The OR operation (||) takes two logical expressions and combines them. If either or both are TRUE, the result is TRUE. Both values must be FALSE for the result to be FALSE. Now we can determine whether the midterm grade is an A or the final grade is an A. If either the midterm grade or the final grade equals A, the assertion is TRUE. In C++, we write the expression like this: |
|
|
|
|
|
|
|
|
midtermGrade == A || finalGrade == A |
|
|
|
|
|
|
|
|
The && and || operators always appear between two expressions; they are binary (two-operand) operators. The NOT operator (!) is a unary (one-operand) operator. It precedes a single logical expression and gives its opposite as the result. If (grade == A) is FALSE, then ! (grade == A) is TRUE. NOT gives us a convenient way of reversing the meaning of an assertion. For example, |
|
|
|
|
|
|
|
|
In some contexts, the first form is clearer; in others, the second makes more sense. |
|
|
|
|
|