
Think together · Start with a story
A ride requires visitors to be at least 120 centimeters tall. If the girl is exactly 120 centimeters, should the robot let her on?
Break down the process
- Read the ruleAt least 120
- Compare120 is greater than or equal to 120
- Resulttrue
A comparison expression produces a true-or-false result. The difference between > and >= is whether the boundary value is included.
01What comparison operators are there?
==
Equal to
!=
Not equal to
<
Less than
>
Greater than
<=
Less than or equal to
>=
Greater than or equal to
02What is the result of a comparison?
5 > 3 // true
5 == 3 // false
7 != 2 // true
A comparison expression evaluates to true or false.
03Do not confuse == and =
=
Assignment: write the value on the right to the left.
==
Comparison: check whether both sides are equal.
x = 5; // assignment
x == 5; // comparison04How can a comparison result control a program?
A common use is with if:
if (score >= 60) {
std::cout << "Passed";
}
The comparison first produces a bool. Then if decides whether to run the code block based on whether it is true or false.
05Can characters be compared too?
Yes. Character types have integer code values, so they can be compared.
'A' < 'B'
In common character encodings, this is true.
Strings, Unicode text, and natural-language sorting are much more complex. Comparing characters is not the whole rule for “dictionary order.”
06Why should you be careful comparing decimals?
Floating-point numbers can only approximate many decimal fractions.
0.1 + 0.2 == 0.3
In common binary floating-point environments, this expression is usually false.
What you have learned
- Comparison operators include
== != < > <= >=. - The result of a comparison is a
bool. =assigns;==compares for equality.- Comparison results are often used in
ifconditions. - Floating-point comparisons need to account for representation error.
Next: &&, ||, !: Combining Multiple Conditions
Your turn to try
If a person's height is 120, what are the results of height > 120 and height >= 120?
Ready? Open to see the explanation
The first is false, and the second is true. Testing a value exactly on the boundary makes the difference easiest to see.