C Reference ยท Types and Literals
C _Bool and bool
Reference for the C boolean type: _Bool, stdbool.h, the C23 bool keyword, how nonzero values convert to 1, and why comparisons still return int.
C99 added a real boolean type called _Bool. A _Bool object holds either 0 or 1, and converting any scalar value to it follows one simple rule: zero becomes 0, everything else becomes 1. That makes it safer than storing a flag in an int or char.
Before C23 you wrote bool, true and false by including <stdbool.h>, which defined them as macros. In C23, bool, true and false are keywords, and the header is still accepted but does nothing. In C, conditions are still tested against zero, so any scalar works in if and while.
bool ready = true; /* C23: no header needed */ if (ready) { /* ... */ }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
_Bool flag = 1; /* C99 and later */ #include <stdbool.h> /* pre-C23: bool, true, false macros */ bool ok = true; /* C23: keywords */
| Name | Description |
|---|---|
_Bool |
The original keyword (C99). Always available. |
bool |
Keyword in C23; macro for _Bool from <stdbool.h> before that. |
true, false |
Keywords in C23 (type bool); macros expanding to 1 and 0 before. In C23 they have type bool. |
__bool_true_false_are_defined |
Macro set to 1 by <stdbool.h>. |
Returns: not applicable. The type has two values, 0 and 1.
Errors / undefined behavior: none for ordinary use. Copying arbitrary bytes into a bool object (for example with memcpy) can create a value other than 0 or 1, which is undefined behavior when read.
Usage notes
- Conversion normalizes.
bool b = 5;stores1, whereaschar c = 5;stores5. This is the main reason to preferboolfor flags. - Relational and logical operators return
int, notbool, in C.sizeof(3 > 2)issizeof(int). Their value is always exactly0or1. - Size is at least one byte, because it must be addressable. It is typically 1 on mainstream compilers, but the standard does not fix it; arrays of
boolare not bit-packed. - Pre-C23 projects still need
#include <stdbool.h>. Code that includes it keeps working in C23, so including it is harmless for portability. - Do not define your own
true/falsemacros or enums in C23 code; they clash with the keywords. - Printing: there is no
%b-style specifier for booleans. Print with%d, or choose a string withb ? "true" : "false". Theboolargument is promoted tointinprintf. - Bit-fields: a
boolbit-field of width 1 can hold only0or1; see bit-fields.