Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Keywords and Statements

bool, true and false

Reference for C boolean values: bool, true and false as keywords in C23, _Bool and <stdbool.h> before, conversions to 0 and 1, and pitfalls.

C23 makes bool, true and false real keywords. bool is an unsigned integer type that can hold only 0 and 1, and true and false are constants of that type with values 1 and 0. Before C23 the type was spelled _Bool (C99), and you included <stdbool.h> to get the macros bool, true and false.

The special property of bool is its conversion rule: any nonzero value converts to 1, zero converts to 0. That makes it different from storing a result in unsigned char, where 256 becomes 0.

C
bool ready = true;
bool any = 42;          /* 1 */

Try it

C Conversion to bool

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.

C Comparisons and logical operators produce int

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

C
bool name = true;            /* C23 */
_Bool name = 1;              /* C99 and later */
#include <stdbool.h>         /* before C23: defines bool, true, false */
Name Description
bool Keyword in C23; macro for _Bool in <stdbool.h> before.
true Constant with value 1 and type bool (C23); int 1 in earlier macro form.
false Constant with value 0.
__bool_true_false_are_defined Macro defined as 1 by <stdbool.h>; kept as an obsolescent feature.

Returns: values of bool are always 0 or 1.

Errors: none at runtime. Pre-C23 code that defines its own bool, true or false (for example typedef int bool; or an enum) will not compile in C23 mode.

Usage notes

  • Storage. sizeof(bool) is 1 on mainstream platforms (the standard only requires it be large enough for 0 and 1).
  • Comparisons yield int. a < b, !x, x && y have type int in C, not bool, with value 0 or 1.
  • Conditions still use "nonzero is true". if (n), while (ptr) and if (!s) work on any scalar; there is no need to compare against true. Writing x == true is wrong for x = 2.
  • Old code. Replace typedef enum { false, true } bool; and #define bool int when moving to C23, or build with -std=c17.
  • printf. There is no %b for bool; print it with %d, or "%s" with a ternary, as the example does.
  • Portability to C++. bool is a C++ keyword with the same meaning, but its sizeof is implementation-defined too.
  • Bit tricks. bool as a bit-field bool flag : 1; is allowed and behaves as expected.