Learn how to use booleans in C and discover the native support introduced in C99.
C, originally, did not have built-in boolean values. However, with the release of C99 in 1999/2000, a boolean type was introduced. Although it requires importing a header file, it is commonly referred to as a “native” boolean type. Let’s explore how to use it.
To begin, include the necessary header files:
#include <stdio.h>
#include <stdbool.h>
Now, you can use the bool
type as follows:
int main(void) {
bool isDone = true;
if (isDone) {
printf("done\n");
}
isDone = false;
if (!isDone) {
printf("not done\n");
}
}
Note that if you are programming for Arduino, you can simply use the bool
type without including stdbool.h
because it is a valid and built-in C++ data type. The Arduino Language is based on C++.
However, in standard C, make sure to include #include <stdbool.h>
to avoid errors when declaring and using bool
variables. Otherwise, you may encounter error messages like the following:
➜ ~ 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.
By utilizing the boolean type in C, you can better express conditions and make your code more readable.
Tags: C boolean, C99, boolean type, header file, bool variable