C ยท Chapter 11 of 45

C Booleans

C does not have a dedicated boolean type in its earliest standards; instead, 0 means false and any nonzero value means true. Modern C (C99 and later) provides _Bool and the more readable `bool` type via the <stdbool.h> header.

Boolean logic is central to control flow, since conditions in if statements and loops are evaluated as true or false.

Syntax
#include <stdbool.h>
bool flag = true;

Truthy and falsy values

In C, the integer 0 is treated as false, and any other value (positive or negative) is treated as true. Comparison expressions like a > b naturally produce 1 or 0.

Using stdbool.h

Including <stdbool.h> lets you use the keywords bool, true and false for more readable code, though internally they still map to integers.

Example 1 (c)
#include <stdio.h>

int main() {
  int isReady = 1;
  if (isReady) {
    printf("Ready!\n");
  }
  return 0;
}
Output
Ready!

A nonzero value 1 is treated as true in the if condition.

Example 2 (c)
#include <stdio.h>
#include <stdbool.h>

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

stdbool.h makes boolean code more readable; false prints as 0.

Key points

  • 0 is false; any nonzero value is true.
  • <stdbool.h> introduces bool, true and false keywords.
  • Comparison operators return 1 or 0.
  • Booleans are stored as small integers under the hood.
๐Ÿ’ก Note: Using <stdbool.h> is recommended for readability even though C's booleans are really just integers.

๐Ÿ“ Quick Quiz

1. In classic C, which value represents false?

2. Which header introduces the bool keyword?

3. What does the expression (5 > 3) evaluate to?