Codiqo

Learn C · lesson 9 of 60 · about 7 minutes

Comparisons and Booleans

Let your report flag low disk space: compare values, store the answer in a bool, and see why C prints it as 1 or 0.

What you'll learn

  • Use the six comparison operators
  • Know that true is 1 and false is 0
  • Declare bool variables

Yes-or-no questions

Your report knows how much space is free, but not whether that's a problem. A comparison answers a question like is the free space under 1024 KiB? In C the answer is a plain number.

Asking questions about values

| Operator | Means |
|---|---|
| == | equal to |
| != | not equal to |
| < | less than |
| > | greater than |
| <= | less than or equal to |
| >= | greater than or equal to |

In C, a comparison gives an int: 1 for true and 0 for false.

Comparisons are numbers

#include <stdio.h>

int main(void) {
    int score = 72;
    printf("%d\n", score > 50);
    printf("%d\n", score == 100);
    printf("%d\n", score != 0);
    return 0;
}

Output

1
0
1

The bool type

#include <stdbool.h> gives you the type bool and the words true and false. They're still 1 and 0 underneath, but they make your intent clear.

A low-space flag

#include <stdio.h>
#include <stdbool.h>

int main(void) {
    int free_kib = 900;
    bool low_space = free_kib < 1024;
    printf("Low on space: %d\n", low_space);
    return 0;
}

Output

Low on space: 1

Tip

== compares and = assigns. Writing if (x = 5) by mistake sets x to 5, and compilers warn about it for good reason.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.