Lesson 43 +10 XP

Comparison Operators

Comparison Operators

Comparison operators compare two values and produce a result: 1 (true) or 0 (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 <stdio.h>

int main() {
  int x = 5;
  int y = 3;
  printf("%d\n", x == y);   // 0 (false)
  printf("%d\n", x != y);   // 1 (true)
  printf("%d\n", x > y);    // 1 (true)
  printf("%d\n", x <= y);   // 0 (false)
  return 0;
}

The answer is 1 or 0

Every comparison gives 1 or 0. 1 means true, 0 means false.

Careful with chaining

Writing 5 < 3 < 2 is a trap. C evaluates the left part first: 5 < 3 is 0 (false), and 0 < 2 is then 1 (true)! For multiple checks, use logical operators or split the condition.

TL;DR

  • Comparison operators: ==, !=, >, <, >=, <=.
  • They always produce 1 (true) or 0 (false).
  • Do not chain comparisons like a < b < c.