C Booleans
Very often in programming you need a value that can only be one of two things: yes or no, on or off, true or false. This kind of value is called a boolean. In C, booleans are stored as ordinary integers, but modern C gives you a friendlier way to work with them.
How C represents true and false
C did not always have a dedicated boolean type. Under the hood, C treats the number 0 as false and any non-zero number as true. That rule is simple but powerful: an integer variable holding 5, -3, or 1 all count as true, while only 0 counts as false.
- 0 means false.
- Any value that is not 0 (like 1, 42, or -7) means true.
- Comparisons such as 10 > 9 produce the value 1 for true and 0 for false.
Comparisons return 1 or 0
#include <stdio.h>
int main() {
printf("%d\n", 10 > 9); // 1 (true)
printf("%d\n", 10 == 9); // 0 (false)
printf("%d\n", 10 < 9); // 0 (false)
return 0;
}The bool type from stdbool.h
Since C99, you can include the header <stdbool.h> to use the keyword bool along with the words true and false. This makes your code much easier to read, because the intent is spelled out clearly instead of relying on 1 and 0.
Using bool, true, and false
#include <stdio.h>
#include <stdbool.h>
int main() {
bool isLearning = true;
bool isTired = false;
printf("%d\n", isLearning); // 1
printf("%d\n", isTired); // 0
return 0;
}Booleans from comparisons
The most common way to get a boolean is to compare two values. The result of a comparison can be stored in a bool variable and used later in your program, which is the foundation of decision making.
Comparing two ages
#include <stdio.h>
#include <stdbool.h>
int main() {
int myAge = 25;
int voteAge = 18;
bool canVote = myAge >= voteAge;
printf("Can vote: %d\n", canVote); // 1
return 0;
}Exercise: C Booleans
Without including <stdbool.h>, does standard C have a built-in keyword called bool?