Booleans in C
What Are Booleans?
A **Boolean** represents truth values: true or false. While C did not originally have a dedicated Boolean type, C99 introduced `_Bool` and `
In C, any non-zero value is considered **true**, and zero is **false** when used in a Boolean context (conditions, logical operators, etc.).
Boolean Implementation Before C99
Before C99, programmers simulated Booleans using integers:
• `0` meant false.
• Any nonzero integer (commonly `1`) meant true.
#include <stdio.h>
int main(void) {
int isValid = 1; // true
int isEmpty = 0; // false
if (isValid) printf("Valid!");
if (!isEmpty) printf(" Not empty!");
printf("\n");
return 0;
}
Valid! Not empty!
Using stdbool.h
Since C99, the standard header `
This improves readability and makes intent clearer.
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool isOn = true;
bool hasItems = false;
printf("isOn=%d, hasItems=%d\n", isOn, hasItems); // printed as 1/0
return 0;
}
isOn=1, hasItems=0
Booleans in Expressions
Boolean expressions result from comparison or logical operators.
Examples: `x > 0`, `x == y`, `flag && ready`.
Booleans are commonly used in `if`, `while`, `for`, and conditional (?:) expressions.
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int a = 5, b = 7;
bool result = (a < b); // true
if (result) {
printf("a is less than b\n");
}
return 0;
}
a is less than b
Truthiness & Normalization
`_Bool`/`bool` stores only `0` or `1`. Assigning any nonzero value to a `bool` is **normalized** to `1`.
Conditions treat any nonzero integer as true and zero as false.
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool b1 = 2; // normalized to 1
bool b2 = -5; // normalized to 1
bool b3 = 0; // stays 0
printf("b1=%d b2=%d b3=%d\n", b1, b2, b3);
int x = 42;
if (x) {
printf("x is truthy\n");
}
return 0;
}
b1=1 b2=1 b3=0 x is truthy
Best Practices
• Use `#include
• Don’t rely on specific integer values for true; any nonzero is true. Avoid `if (flag == 1)`; prefer `if (flag)`.
• Print with `%d` unless you create custom helpers for "true/false" strings.
• When working with flags, prefer `bool` over `int` to signal intent.
• Use parentheses to make complex logical expressions with `&&`/`||` unambiguous.