Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating Expressions and Statements 93

4


It might be that the programmer wanted this expression to evaluate true if both xand y
are greater than 5 or if zis greater than 5. On the other hand, the programmer might have
wanted this expression to evaluate true only if xis greater than 5 and if it is also true that
either yis greater than 5 or zis greater than 5.
If xis 3, and yand zare both 10, the first interpretation is true (zis greater than 5 ,so
ignore xand y), but the second is false (it isn’t true that xis greater than 5 , and thus it
doesn’t matter what is on the right side of the &&symbol because both sides must be
true).
Although precedence determines which relation is evaluated first, parentheses can both
change the order and make the statement clearer:
if ( (x > 5) && (y > 5 || z > 5) )
Using the values from earlier, this statement is false. Because it is not true that xis
greater than 5 , the left side of the ANDstatement fails, and thus the entire statement is
false. Remember that an ANDstatement requires that both sides be true—something isn’t
both “good tasting”AND“good for you” if it isn’t good tasting.

It is often a good idea to use extra parentheses to clarify what you want to
group. Remember, the goal is to write programs that work and that are easy
to read and to understand. Using parentheses help to clarify your intent and
avoid errors that come from misunderstanding operator precedence.

TIP


More About Truth and Falsehood ..........................................................................


In C++, zero evaluates to false, and all other values evaluate to true. Because an expres-
sion always has a value, many C++ programmers take advantage of this feature in their
ifstatements. A statement such as
if (x) // if x is true (nonzero)
x = 0;
can be read as “If xhas a nonzero value, set it to 0 .” This is a bit of a cheat; it would be
clearer if written
if (x != 0) // if x is not zero
x = 0;
Both statements are legal, but the latter is clearer. It is good programming practice to
reserve the former method for true tests of logic, rather than for testing for nonzero
values.
Free download pdf