Learn C++
#include "operators/op_comparison.hpp"

Comparison Operators in C++

//concept

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.

//how it works
1

The six classic operators

== != < <= > >= each yield a bool. They chain naturally into conditions like low <= x && x <= high.

2

The spaceship <=>

C++20's (a <=> b) returns less, equal, or greater at once; defaulting it in a class generates every comparison automatically.

3

= 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.

4

Never == on doubles

0.1 + 0.2 != 0.3 in binary floating point. Test std::abs(a - b) < 1e-9 instead of exact equality.

//example
#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;
}
Output
1
1
1
1score >= 60 is true (85 passes), printing 1 since bools print as 1/0 by default.
2score == 85 compares rather than assigns, correctly yielding true.
3score != 100 is also true — all three comparisons agree and print 1.
//use cases
Gatekeeping branches and loop exits on threshold checks like score >= pass
Sorting and ordered containers, which lean on < (or <=>) to rank elements
Guarding floating-point tests with epsilon comparisons instead of ==
Defining <=> once per class and getting every comparison operator for free

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.