Comparison Operators
Lesson outline
Introduction to Comparison Operators
Comparison operators are used to compare two values. These operators return a boolean value (true or false) depending on the result of the comparison.
They are essential in decision-making constructs like if, while, and other conditional statements.
Comparison Operators
The main comparison operators in C++ are:
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 5 | true |
| != | Not equal to | 5 != 5 | false |
| > | Greater than | 5 > 3 | true |
| < | Less than | 5 < 3 | false |
| >= | Greater than or equal to | 5 >= 5 | true |
| <= | Less than or equal to | 5 <= 3 | false |
Practical Examples
Comparison operators are often used in variable checks and decision-making logic.
Floating-Point Comparisons
Comparing floating-point numbers directly can be problematic due to precision and rounding. Instead of using ==, compare with a small tolerance (epsilon).
When magnitudes vary a lot, consider a relative tolerance as well.
Common Pitfalls
- Do not write chained comparisons like
0 < x < 10; write0 < x && x < 10. - Be careful comparing signed and unsigned integers; implicit conversions can surprise you.
std::stringcomparisons are lexicographical (dictionary-like), not numeric.- Equality (
==,!=) has lower precedence than relational (<,<=,>,>=); use parentheses for clarity.
Note on C++20 Three-Way Comparison
C++20 introduces the <=> (spaceship) operator for user-defined types, producing an ordering result and enabling consistent generation of ==, <, >, etc. This is advanced usage and not needed for basic comparisons.