| Previous | Table of Contents | Next |
Relational operators and logical operators, being C++ expressions, each return a value: 1 (true) or 0 (false). Like all expressions, they have a precedence order that determines which relations are evaluated first. This fact is important when determining the value of the statement
if ( x > 5 && y > 5 || z > 5)
It might be that the programmer wanted this expression to evaluate true if both x and y are greater than 5 or if z is greater than 5. On the other hand, the programmer might have wanted this expression to evaluate true only if x is greater than 5 and if it is also true that either y is greater than 5 or z is greater than 5.
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 isnt both good tasting AND good for you if it isnt good tasting.
![]() |
|
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.
In this hour you learned what a statement is. You also learned that an expression is any statement that returns a value. You learned that whitespace can be used to make your program more readable, and you saw how to use the mathematical and assignment operators.
You also learned how to use the prefix and postfix operators, as well as the relational operators. You learned how to use the if statement, how to use else, and how to create complex and nested if statements.
if ( (x = a + b) == 35 )
| Previous | Table of Contents | Next |