< previous page page_57 next page >

Page 57
Output:
Enter a number less than 10 or greater than 100: 20
Analysis: The braces on lines 12 and 15 make everything between them into one statement, and now the else on line 16 applies to the if on line 10 as intended.
The user typed 20, so the if statement on line 11 is true; however, the if statement on line 13 is false, so nothing is printed. It would be better if the programmer put another else clause after line 14 so that errors would be caught and a message printed.
The programs shown in this book are written to demonstrate the particular issues being discussed. They are intentionally kept simple; there is no attempt to bulletproof the code to protect against user error. In professional-quality code, every possible user error is anticipated and handled gracefully.

Logical Operators
Often you want to ask more than one relational question at a time. Is it true that x is greater than y, and also true that y is greater than z? A program might need to determine that both of these conditions are true, or that some other condition is true, in order to take an action.
Imagine a sophisticated alarm system that has this logic: If the door alarm sounds AND it is after six p.m. AND it is NOT a holiday, OR if it is a weekend, then call the police. The three logical operators of C++ are used to make this kind of evaluation. These operators are listed in Table 4.2.
TABLE 4.2 THE LOGICAL OPERATORS
OperatorSymbolExample
AND&&expression1 && expression2
OR¦¦expression1 ¦¦ expression2
NOT!!expression

Logical AND
A logical AND statement evaluates two expressions, and if both expressions are true, the logical AND statement is true as well. If it is true that you are hungry, AND it is true that you have money, THEN it is true that you can buy lunch. Thus,

 
< previous page page_57 next page >

If you like this book, buy it!