3.3 — Comparing things
Read one box at a time. No rush.
Comparison operators#
These compare two values and give back a bool (true or false).
| Operator | Means | Example | Result |
|---|---|---|---|
== | equal to | 3 == 3 | true |
!= | not equal to | 3 != 3 | false |
< | less than | 2 < 5 | true |
> | greater than | 2 > 5 | false |
<= | less than or equal | 5 <= 5 | true |
>= | greater than or equal | 4 >= 5 | false |
C++
int age { 16 };std::cout << std::boolalpha;std::cout << (age >= 18) << '\n'; // falsestd::cout << (age == 16) << '\n'; // true= vs ==#
This is the most famous beginner mistake.
=puts a value in a box.==asks "are these equal?"
C++ — wrong ✗
if (score = 100) // puts 100 into score! always trueC++ — right ✓
if (score == 100) // asks: is score 100?Watch out
When comparing, always double-check you typed ==, not =. Turn on compiler warnings (-Wall) to catch this.
Comparing text#
std::string can be compared with == too:
C++
std::string password { "open sesame" };bool correct { password == "open sesame" }; // trueText comparison is exact. "Hello" and "hello" are not equal.
Tip: press ← / → to move between lessons, / to search.