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 tot, and the value of the assignment, 0, counts as false. GCC and Clang warn about this with-Wall.- Chained comparisons.
0 <= t <= 300means(0 <= t) <= 300. The first part is 0 or 1, and both are at most 300, so the whole test is always 1. Write0 <= t && t <= 300. - Mixed types. Comparing a negative
intwith anunsignedconverts 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.
Leftmost comparison
0 <= 450is true, so it becomes 1.
Drills
Answer fast — trust the rule.
What does printf("%d\n", 5 > 3); print?
With int t = 450;, what is the value of 0 <= t <= 300?
What does if (count = 0) { ... } do?
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==, anda <= x <= b, both compile and both are wrong.
