Skip to the workspace
Pebellslearn by building
Operators  ›  Lesson

Comparison Operators

Comparison 10 minComparison operators return the int 1 for true and 0 for false, which is why = versus == and chained comparisons are silent bugs rather than errors.

c / Comparison Operators

Explore each scene at your own pace.

01 · The rule

The rule

Comparison Operators

Comparison operators return the int 1 for true and 0 for false, which is why = versus == and chained comparisons are silent bugs rather than errors.

Compare values with the intended signedness and distinguish comparison from assignment.

The logger must raise an alarm when a reading leaves the safe range. A teammate wrote the check the way a maths textbook would, 0 <= t <= 300, and it compiled without complaint. It also let a reading of 450 through. Comparisons in C are not statements of truth; they are small calculations that produce a number.

The rule

A comparison is a calculation that answers 1 for true, 0 for false.

The six comparison operators:

Operator Meaning t = 215 gives
== equal to t == 215 → 1
!= not equal to t != 215 → 0
< > less, greater t < 300 → 1
<= >= less or equal, greater or equal t >= 300 → 0

The result has type int and is always exactly 1 or 0. You can store it, print it or add it up:

int alarms = 0;
alarms += (t > 300);        /* adds 1 when too hot, 0 otherwise */
printf("%d\n", t < 300);    /* prints 1 */

Three classic traps follow directly from that:

  • = instead of ==. if (t = 0) does not test anything. It assigns 0 to t, and the value of the assignment, 0, counts as false. GCC and Clang warn about this with -Wall.
  • Chained comparisons. 0 <= t <= 300 means (0 <= t) <= 300. The first part is 0 or 1, and both are at most 300, so the whole test is always 1. Write 0 <= t && t <= 300.
  • Mixed types. Comparing a negative int with an unsigned converts it to a huge unsigned value (last section), and comparing floating-point values with == is unreliable (use a tolerance).
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.