|
|
|
|
|
|
|
If x is 3, and y and z are both 10, the first interpretation will be true (z is greater than 5, so ignore x and y), but the second will be false. (It is not true that x is greater than 5, so it does not matter that y or z are greater than 5.) |
|
|
|
|
|
|
|
|
Although precedence will determine 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 given earlier, this statement is false. Because it is not true that x is greater than 5, the left side of the AND statement fails, and thus the entire statement is false. Remember that an AND statement requires that both sides be truesomething 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 understand. |
|
|
|
|
|
|
|
|
|
More About Truth and Falsehood |
|
|
|
|
|
|
|
|
In C++ zero is false, and any other value is true. Because expressions always have a value, many C++ programmers take advantage of this feature in their if statements. A statement such as |
|
|
|
|
|
|
|
|
if (x) // if x is true (nonzero)
x = 0; |
|
|
|
|
|
|
|
|
can be read as If x has 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 nonzero
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. |
|
|
|
|
|
|
|
|
These two statements are also equivalent: |
|
|
|
|
|
|
|
|
if (!x) // if x is false (zero)
if (x == 0) // if x is zero |
|
|
|
|
|
|
|
|
The second statement, however, is somewhat easier to understand and is more explicit. |
|
|
|
|
|