Lesson 41 +10 XP

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

Code

cpp
#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 &lt; 3 &lt; 2 is a trap. C++ evaluates the left part first: 5 &lt; 3 is false, and false &lt; 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 &amp;&amp;.

TL;DR

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