C Comparison Operators

Comparison operators let your program ask questions about values, such as is this bigger than that, or are these two equal. The answer is always either true (1) or false (0). These operators are the foundation of decisions, so you will use them constantly with if statements and loops.

The Comparison Operators

C has six comparison operators. Each one takes two values, compares them, and returns 1 if the comparison is true or 0 if it is false.

OperatorMeaningExampleResult
==Equal to5 == 51
!=Not equal to5 != 31
>Greater than5 > 31
<Less than5 < 30
>=Greater than or equal to5 >= 51
<=Less than or equal to3 <= 20

Comparing values

#include <stdio.h>

int main() {
  int a = 7, b = 4;
  printf("a == b: %d\n", a == b);
  printf("a > b: %d\n", a > b);
  printf("a <= b: %d\n", a <= b);
  return 0;
}

This prints 0, 1, and 0. Because a is 7 and b is 4, they are not equal (0), a is greater than b (1), and a is not less than or equal to b (0).

Comparisons in Decisions

Comparison operators become truly useful inside if statements, where the 1 or 0 result decides which code runs.

Using a comparison in an if

#include <stdio.h>

int main() {
  int temperature = 30;
  if (temperature > 25) {
    printf("It is a hot day!\n");
  }
  return 0;
}
Note: The single = stores a value, while the double == checks for equality. Writing if (x = 5) instead of if (x == 5) is a classic bug: it assigns 5 to x and is always treated as true.
  • Comparison operators always return 1 (true) or 0 (false).
  • Use == to test equality, not the single =.
  • They are most useful inside if statements and loops.