Booleans in C
An introduction to how to use booleans in C
C originally did not have native support for boolean values.
C99, the version of C released in 1999/2000, introduced a boolean type.
To use it, however, you need to import a header file, so I’m not sure we can technically call it “native”. Anyway, we do have a bool
type.
You can use it like this:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool isDone = true;
if (isDone) {
printf("done\n");
}
isDone = false;
if (!isDone) {
printf("not done\n");
}
}
If you’re programming the Arduino, you can use bool
without including stdbool
because bool
is a valid and built-in C++ data type, and the Arduino Language is C++.
In plain C, remember to #include <stdbool.h>
otherwise you’ll get a bunch of errors at declaration and any time you use the bool
variable:
➜ ~ gcc hello.c -o hello; ./hello
hello.c:4:3: error: use of undeclared identifier
'bool'
bool isDone = true;
^
hello.c:5:7: error: use of undeclared identifier
'isDone'
if (isDone) {
^
hello.c:8:8: error: use of undeclared identifier
'isDone'
if (!isDone) {
^
3 errors generated.
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025