Lesson 41 +10 XP

Comparison Operators

C++ Comparison Operators

Comparison operators compare two values and produce a boolean: true or false.

The six comparisons

  • == equal to
  • != not equal to
  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to

Example program

#include <iostream>
using namespace std;

int main() {
  int x = 5;
  int y = 3;
  cout << (x == y) << endl;  // 0 (false)
  cout << (x != y) << endl;  // 1 (true)
  cout << (x > y) << endl;   // 1 (true)
  cout << (x <= y) << endl;  // 0 (false)
  return 0;
}

The answer is a boolean

Every comparison gives back a boolean. Printed, true shows as 1 and false as 0.

Come careful about chaining

Writing 5 < 3 < 2 is a trap. C++ evaluates the left part first: 5 < 3 is false, and false < 2 compares a boolean to a number. The results can fool you. When comparing three things, use the logical operators or write two separate checks and combine them with &&.

TL;DR

  • Comparison operators: ==, !=, >, <, >=, <=.
  • They always return a boolean.
  • true prints 1, false prints 0.
  • Do not chain comparisons like a < b < c.