Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C Booleans

Programs constantly ask yes-or-no questions: is the user old enough, is the list empty, did the file open? A value that is either true or false is called a boolean.

True and false are numbers

In C, a condition is just a number: 0 means false, and any other number means true. Comparisons give exactly 1 or 0.

#include <stdio.h>

int main(void) {
    int x = 10, y = 9;
    printf("%d\n", x > y);
    printf("%d\n", x == y);
    printf("%d\n", 10 == 10);
    return 0;
}
Output
1
0
1

The bool type

Since C99, the header stdbool.h gives a proper type bool and the words true and false. Using them makes code easier to read. A bool is printed with %d, so it shows as 1 or 0.

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

int main(void) {
    bool isRaining = false;
    bool haveUmbrella = true;
    int age = 17;
    bool canVote = age >= 18;

    printf("can vote: %d\n", canVote);
    if (!isRaining || haveUmbrella) {
        printf("You can go out.\n");
    }
    return 0;
}
Output
can vote: 0
You can go out.

(Since C23, bool, true and false are built into the language and the header is no longer needed, but including it is still correct.)

Using booleans in decisions

Booleans shine in if statements and loops, covered in the next topics. A boolean variable with a good name reads like a sentence: if (isValid), while (!finished). Writing if (isValid == true) works too, but it is longer and says nothing more.

Remember that any non-zero number counts as true. if (count) means "if count is not zero", which you will see often in C code.

Common mistakes

  • Writing if (x = 0) instead of if (x == 0): the first stores 0 and is always false.
  • Testing a range as if (10 < x < 20): C reads it as (10 < x) < 20, which is always true because 10 < x is 0 or 1. Write if (x > 10 && x < 20).
  • Comparing decimal numbers with ==: 0.1 + 0.2 == 0.3 is false, because decimals are stored approximately. Check that the difference is very small instead.

Practice exercises

  1. Store whether a number is even in a bool and print it.
  2. Create bool hasTicket and int age, and print 1 if the person may enter: they need a ticket and must be at least 12.
  3. Print the value of !0 and !5. Explain the results.