Booleans in C

By

Learn how to use booleans in C, where the bool type added in C99 needs #include <stdbool.h> before you can use true and false in your programs.

~~~

C originally did not have native support for boolean values. C99, the version of C released in 1999/2000, introduced a boolean type, and to use it you include the stdbool.h header file.

What did C programmers do before?

In C, any nonzero value is true, and 0 is false. So historically people used int variables as flags:

int isDone = 1;
if (isDone) { /* ... */ }

Many codebases defined their own TRUE and FALSE macros on top of that. It worked, but every project did it slightly differently.

C99 fixed this by adding a real boolean type, called _Bool, plus the stdbool.h header, which defines bool, true and false as friendlier names for it.

Since you need to import a header file to use it, I’m not sure we can technically call it “native”. Anyway, we do have a bool type.

How to use bool

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");
  }
}

A bool can only hold 0 or 1. Assign it any nonzero value and it becomes 1:

bool active = 42;
printf("%d\n", active); /* 1 */

This matters more than it looks. With an int flag holding 42, a comparison like flag == TRUE is false, because 42 is not 1, even though the flag is “true”. With bool the value is normalized, so that whole class of bugs goes away.

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++.

What if you forget the include?

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.

The compiler has no idea what bool means, so every line touching the variable errors out. Adding the include at the top fixes all of them at once.

One last note: C23, the latest revision of the standard, finally makes bool, true and false proper keywords. If your compiler targets C23 you don’t need the header anymore. For older standards, keep the include.

Tagged: C · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about clang: