Chapter 3
Chapter 3
Relational Operators
cont’d
Here there are some examples:
1 (2.5 == 5.8) // evaluates to false
2 (5 > 4) // evaluates to true
3 (3 != 2) // evaluates to true
4 (6 >= 6) // evaluates to true
5 ('R’ > 'T’) // evaluates to false
Of course, it's not just numeric constants that can be compared,but just any value,
including, of course, variables. Suppose that a=2, b=3 and c=6, then:
1 (a == 5) // evaluates to false, since a is not equal to 5
2 (a*b >= c) // evaluates to true, since (2*3 >= 6) is true
3 (b+4 > a*c) // evaluates to false, since (3+4 > 2*6) is false
4 ((b=2) == a) // evaluates to true
Logical (Boolean) Operators and Logical
Expressions
• Logical (Boolean) operators: let you combine
logical expressions.
The ! (Not) Operator
The && (And) Operator
The || (Or) Operator
Precedence of Some Operators
Precedence of Operators (cont’d.)
Precedence of Operators (cont’d.)
Precedence of Operators (cont’d.)
Short-Circuit Evaluation
• Short-circuit evaluation: evaluation of a logical
expression stops as soon as the value of the
expression is known.
• Example:
(age >= 21) || ( x == 5) //Line 1
(grade == 'A') && (x >= 7) //Line 2
Three Common Mistakes
• The next three slides discuss three common
mistakes:
1. Comparing floating-point numbers for equality.
2. Associativity of relational operators.
3. Confusing equality (==) with assignment (=).
Comparing Floating-Point Numbers for
Equality: A Precaution
• Comparison of floating-point numbers for equality
may not behave as you would expect.
– Example:
• 1.0 == 3.0/7.0 + 2.0/7.0 + 2.0/7.0 evaluates to
false
• Why? 3.0/7.0 + 2.0/7.0 + 2.0/7.0 =
0.99999999999999989
• Solution: either avoid doing this, or use a tolerance
value instead:
– Example: if fabs(x – y) < 0.000001
Associativity of Relational Operators: A
Precaution
Associativity of Relational Operators: A
Precaution (cont’d.)
• Suppose num = 5:
36
switch Structures (cont’d.)
• One or more statements may follow a case label.
• Braces are not needed to turn multiple statements into
a single compound statement.
• When a case value is matched, all statements after it
execute until a break is encountered.
• The break statement may or may not appear after
each statement.
• switch, case, break, and default are reserved
words.
switch Structures (cont’d.)
Avoiding Bugs: Revisited
• To output results correctly:
– Consider whether the switch structure must
include a break statement after each cout
statement.