C++ Comparison Operators
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.
#include <iostream>
using namespace std;
int main() {
int age = 18;
bool isAdult = (age >= 18);
double temp = 25.5;
bool isWarm = (temp > 20.0);
cout << boolalpha; // print true/false instead of 1/0
cout << "Is adult: " << isAdult << '\n';
cout << "Is warm: " << isWarm;
return 0;
}
Is adult: true Is warm: true
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.
#include <iostream>
#include <cmath>
using namespace std;
bool almost_equal(double a, double b, double abs_eps = 1e-9, double rel_eps = 1e-9) {
double diff = fabs(a - b);
return diff <= max(abs_eps, rel_eps * max(fabs(a), fabs(b)));
}
int main() {
double a = 0.1 + 0.1 + 0.1;
double b = 0.3;
cout << boolalpha;
cout << "a == b: " << (a == b) << '\n';
cout << "Almost equal: " << almost_equal(a, b);
return 0;
}
a == b: false Almost equal: true
Common Pitfalls
- Do not write chained comparisons like `0 < x < 10`; write `0 < x && x < 10`.
- Be careful comparing signed and unsigned integers; implicit conversions can surprise you.
- `std::string` comparisons 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.