< previous page page_58 next page >

Page 58
if ( (x == 5) && (y == 5) )
would evaluate true if both x and y are equal to 5, and it would evaluate false if either one is not equal to 5. Note that both sides must be true for the entire expression to be true.
Note that the logical AND is two && symbols.
Logical OR
A logical OR statement evaluates two expressions. If either one is true, the expression is true. If you have money OR you have a credit card, you can pay the bill. You don't need both money and a credit card; you need only one, although having both would be fine as well. Thus,
if ( (x == 5) ¦¦ (y == 5) )
evaluates true if either x or y is equal to 5, or if both are equal to five. In fact, if x is equal to five, the compiler will never check on y at all!
Note that the logical OR is two ¦¦ symbols.
Logical NOT.
A logical NOT statement 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 x is not equal to 5. This is exactly the same as writing
if (x != 5)
Relational Precedence
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.

 
< previous page page_58 next page >

If you like this book, buy it!