🎓 A1Learner
🔍
0 of 50 lessons completed

C Booleans

Operators did jobs on numbers. A bool holds true or false, and nothing else, and the type comes from stdbool.h.

A bool holds true

ready holds true, and true prints as 1 with %d.

#include <stdio.h>
#include <stdbool.h>

int main() {
  bool ready = true;
  printf("%d\n", ready);
  return 0;
}

A bool holds false

done holds false, and false prints as 0 with %d.

#include <stdio.h>
#include <stdbool.h>

int main() {
  bool done = false;
  printf("%d\n", done);
  return 0;
}

Two bools in one program

sunny holds true and rainy holds false. The prints show 1 then 0, one for each value.

#include <stdio.h>
#include <stdbool.h>

int main() {
  bool sunny = true;
  bool rainy = false;
  printf("%d\n", sunny);
  printf("%d\n", rainy);
  return 0;
}

Example

#include <stdio.h>
#include <stdbool.h>

int main() {
  bool lightOn = true;
  bool doorLocked = false;
  printf("Light: %d\n", lightOn);
  printf("Locked: %d\n", doorLocked);
  return 0;
}

Key points

  • A bool is a type that holds only true or false.
  • The line #include <stdbool.h> adds the bool type to the program.
  • true stands for yes, and false stands for no.
  • A bool variable is declared like any other variable, with bool in front of the name.
  • Printing a bool with %d shows 1 for true and 0 for false.
  • Use a bool for a value that has only two sides, like on or off.

lightOn holds true and doorLocked holds false. The first line prints 1 for true, and the second prints 0 for false.

Note

Without stdbool.h, the words true and false have no meaning in C.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line creates a bool named ready that holds true?