Lesson 34 +10 XP

Booleans in C

Booleans in C

C didn't always have a true bool type. Today, with <stdbool.h>, you can use bool, true, and false.

Using bool

#include <stdbool.h>

bool isSunny = true;
bool hasRain = false;

The old way: 0 and 1

Historically, C used integers for booleans: 0 is false, and any non-zero value is true.

int flag = 1;      // true
int off = 0;       // false

In conditions

if, while, and for all expect a "truthy" value:

int score = 10;
if (score) {          // true, since score is non-zero
    printf("You have points!");
}

Printing booleans

Print %d to see 1 (true) or 0 (false):

printf("%d\n", isSunny);   // 1

TL;DR

  • Include <stdbool.h> for bool, true, false.
  • Historically, 0 = false, anything non-zero = true.
  • Conditions accept any non-zero value as true.
  • Printing a bool with %d shows 1 or 0.