Sams Teach Yourself C++ in 21 Days

(singke) #1
Note that the logical ORis two ||symbols. A single |symbol is a different operator,
which is discussed on Day 21.

The Logical NOTOperator ................................................................................


A logicalNOTstatement evaluates true if the expression being tested is false. Again, if the
expression being tested is false, the value of the test is true! Thus,
if ( !(x == 5) )
is true only if xis not equal to 5. This is the same as writing
if (x != 5)

Short Circuit Evaluation ........................................................................................


When the compiler is evaluating an ANDstatement, such as
if ( (x == 5) && (y == 5) )
the compiler evaluates the truth of the first statement (x==5), and if this fails (that is, if x
is not equal to 5 ), the compiler does NOTgo on to evaluate the truth or falsity of the sec-
ond statement (y == 5) because ANDrequires both to be true.
Similarly, if the compiler is evaluating an ORstatement, such as
if ( (x == 5) || (y == 5) )
if the first statement is true (x == 5), the compiler never evaluates the second statement
(y == 5) because the truth of eitheris sufficient in an ORstatement.
Although this might not seem important, consider the following example:
if ( (x == 5 )|| (++y == 3) )
If xis not equal to 5 , then (++y == 3)is not evaluated. If you are counting on yto be
incremented regardless, it might not happen.

Relational Precedence............................................................................................


Like all C++ expressions, the use of relational operators and logical operators each return
a value:trueor false. Like all expressions, they also have a precedence order (see
Appendix C) that determines which relations are evaluated first. This fact is important
when determining the value of statements such as the following:
if ( x > 5 && y > 5 || z > 5)

92 Day 4

Free download pdf