Comparison Operators in C++
Comparisons (==, !=, <, <=, >, >=) evaluate to bool and drive every if, loop condition, and assertion. C++20 added the three-way comparison operator <=>, the spaceship, which reports less/equal/greater in one expression and lets the compiler auto-generate all six comparisons for a class — a huge upgrade for ordered types.
Two evergreen traps: assignment (=) where equality (==) was meant, which the compiler usually warns about inside if, and comparing floating-point values for exact equality, which fails on rounding dust — compare with an epsilon instead.
The six classic operators
== != < <= > >= each yield a bool. They chain naturally into conditions like low <= x && x <= high.
The spaceship <=>
C++20's (a <=> b) returns less, equal, or greater at once; defaulting it in a class generates every comparison automatically.
= vs ==
if (x = 5) assigns and tests 5 (always true) instead of comparing — modern compilers warn, and Yoda conditions (5 == x) make typos fail loudly.
Never == on doubles
0.1 + 0.2 != 0.3 in binary floating point. Test std::abs(a - b) < 1e-9 instead of exact equality.
#include <iostream> int main() { int score = 85; std::cout << (score >= 60) << std::endl; std::cout << (score == 85) << std::endl; std::cout << (score != 100) << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.