Skip to content

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.
→ Download my free C Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about clang: