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;
}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;
}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 ofif (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 because10 < xis 0 or 1. Writeif (x > 10 && x < 20). - Comparing decimal numbers with
==:0.1 + 0.2 == 0.3is false, because decimals are stored approximately. Check that the difference is very small instead.
Practice exercises
- Store whether a number is even in a
booland print it. - Create
bool hasTicketandint age, and print1if the person may enter: they need a ticket and must be at least 12. - Print the value of
!0and!5. Explain the results.