Before a program can make a choice, it must ask a question like "is the age at least 18?". We ask these questions with comparison operators:
| Operator | Means | Example | Answer |
|---|---|---|---|
== | is equal to | 5 == 5 | true (1) |
!= | is not equal to | 5 != 3 | true (1) |
< | is less than | 2 < 1 | false (0) |
> | is greater than | 9 > 4 | true (1) |
<= | is less than or equal to | 3 <= 3 | true (1) |
>= | is greater than or equal to | 2 >= 8 | false (0) |
In C, a comparison gives back a number: 1 for true and 0 for false:
#include <stdio.h>
int main() {
int age = 20;
printf("%d\n", age >= 18);
printf("%d\n", age == 30);
printf("%d\n", age != 30);
return 0;
}Output
1 0 1
Common mistake: Mixing up
=and==. One=puts a value in a variable. Two==ask whether two values are equal.
Think of it like this:
=is like saying "the box now holds 5".==is like asking "does the box hold 5?"