Site Tools


wiki:stdbool.h

Table of Contents

stdbool.h

Before C99, every codebase had its own boolean convention. Some used int with 0 for false and non-zero for true, some #defined TRUE and FALSE, some used char. stdbool.h (C99) ends that by giving portable names to the convention the language already used: bool, true, and false.

#include <stdbool.h>
 
bool connected = false;
 
bool check_connection(int fd) {
    if (fd < 0) return false;
    return true;
}
 
connected = check_connection(sock);
if (connected) { ... }

Under the hood, bool expands to _Bool, a genuine C99 keyword that stores only 0 or 1. Assigning any non-zero value to it produces 1 — unlike int, where 42 stays 42:

_Bool x = 5;    // x is 1, not 5
bool  y = 5;    // same: y is 1
int   z = 5;    // z is 5

In C23, bool, true, and false became built-in keywords, making <stdbool.h> technically redundant. The header remains valid and gets included widely — it just defines macros that expand to the keywords. Including it costs nothing and keeps code readable on C99 through C23.

Practice

// compile: gcc -std=c99 -o booltest booltest.c
// run: ./booltest
// description: show that _Bool truncates to 0/1 regardless of the assigned value
 
#include <stdbool.h>
#include <stdio.h>
 
int main(void) {
    bool a = 42;
    bool b = -1;
    bool c = 0;
    int  d = 42;
 
    printf("bool(42) = %d\n", a);   // 1
    printf("bool(-1) = %d\n", b);   // 1
    printf("bool(0)  = %d\n", c);   // 0
    printf("int(42)  = %d\n", d);   // 42
    return 0;
}

bool(42) and bool(-1) both print 1. This matters if you store the result of a function that returns multiple non-zero error codes — bool collapses them all to 1, which may or may not be what you intended.

wiki/stdbool.h.md · Last modified: by 127.0.0.1