3.3 — Comparing things

📘 Chapter 3⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Comparison operators#

These compare two values and give back a bool (true or false).

OperatorMeansExampleResult
==equal to3 == 3true
!=not equal to3 != 3false
<less than2 < 5true
>greater than2 > 5false
<=less than or equal5 <= 5true
>=greater than or equal4 >= 5false
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 true
C++ — 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" };   // true

Text comparison is exact. "Hello" and "hello" are not equal.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.