Adds the bool type and true/false constants to C. Available since C99.
Include: #include <stdbool.h> | Compile: gcc -Wall -o prog prog.c
| Name | Prototype / Value | Description |
|---|---|---|
| bool | typedef _Bool bool | Boolean type (0 or 1) |
| true | #define true 1 | Boolean true constant |
| false | #define false 0 | Boolean false constant |
Copy, save as demo.c, and compile with the command shown at the bottom.
#include <stdio.h>
#include <stdbool.h>
bool is_even(int n) { return (n % 2 == 0); }
bool is_prime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
int main(void) {
for (int i = 1; i <= 20; i++) {
printf("%2d: even=%-5s prime=%s\n",
i,
is_even(i) ? "true" : "false",
is_prime(i) ? "true" : "false");
}
return 0;
}
/* Compile: gcc -Wall -std=c99 -o bool_demo bool_demo.c */