Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

Comparison Operators

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).

The shortcut

Evaluate each comparison to 0 or 1 before looking at the next operator. Comparisons of the same kind group left to right, so replace the leftmost one with its number and keep going.

Why 0 <= t <= 300 passes t = 450Step 1 of 4
  1. Leftmost comparison

    0 <= 450 is true, so it becomes 1.

Drills

Answer fast — trust the rule.

quick drill

What does printf("%d\n", 5 > 3); print?

quick drill

With int t = 450;, what is the value of 0 <= t <= 300?

quick drill

What does if (count = 0) { ... } do?

quick drill

What is (3 == 3) + (2 > 5) + (4 != 4)?

Remember

  • A comparison is a calculation that answers 1 for true, 0 for false.
  • Shortcut: turn each comparison into 0 or 1, left to right, before reading on.
  • Trap: = versus ==, and a <= x <= b, both compile and both are wrong.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe range check that always passes

A teammate wrote if (0 <= t <= 300) to check that a reading is between 0 and 300 tenths. Explain why it accepts t = 450, and write the correct test.