C++ Comparison Operators

Comparison operators check how two values relate to each other. Is one bigger? Are they equal? Every answer is either true or false, which makes these operators the foundation of decisions and loops in your programs.

Comparing values

A comparison operator takes two values and returns a bool, which is either true (shown as 1) or false (shown as 0). You will use these results inside if statements and loops to control what your program does.

Comparison operators

OperatorMeaningExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
>Greater than5 > 8false
<Less than5 < 8true
>=Greater than or equal5 >= 5true
<=Less than or equal3 <= 2false

Printing comparison results

#include <iostream>
using namespace std;

int main() {
  int a = 7;
  int b = 10;

  cout << (a == b) << "\n"; // 0 (false)
  cout << (a != b) << "\n"; // 1 (true)
  cout << (a < b)  << "\n"; // 1 (true)
  cout << (a >= b) << "\n"; // 0 (false)
  return 0;
}

By default cout prints a bool as 1 or 0. That is normal. What matters is that these operators give you a clear true or false answer you can act on.

Using a comparison in a decision

#include <iostream>
using namespace std;

int main() {
  int age = 18;

  if (age >= 18) {
    cout << "You are an adult.\n";
  } else {
    cout << "You are a minor.\n";
  }
  return 0;
}
  • == checks equality, while = assigns a value
  • != means not equal to
  • Comparison results are always a bool (true or false)
  • These operators power almost every if statement you will write
Note: A classic bug is writing if (x = 5) when you meant if (x == 5). The first assigns 5 to x and is always true. Double-check your equals signs whenever a condition behaves strangely.