It seems a bit clickbaity; to be precise, there is no bool keyword in the C language standard to represent boolean types. In C++, we usually use bool variables to store logical values. However, there is no bool type in C; C only has the _Bool type. Today, when discussing this issue with someone, it can indeed be confusing, so I’m writing it down for future reference.
[ISO/IEC 9899:2011(E) §7.18] Boolean type and values <stdbool.h>
The header <stdbool.h> defines four macros. The macro
boolexpands to_Bool. The remaining three macros are suitable for use in#ifpreprocessing directives. They aretruewhich expands to the integer constant 1,falsewhich expands to the integer constant 0, and__bool_true_false_are_definedwhich expands to the integer constant 1. Notwithstanding the provisions of 7.1.3, a program may undefine and perhaps then redefine the macros bool, true, and false.259)
[C Primer Plus 5th P46]_Bool type was introduced with C99 to represent boolean values, meaning C uses the value 1 to represent true and the value 0 to represent false; thus, the _Bool type is also an integer type. In principle, they only need 1 bit for storage.
Because for 0 and 1, 1 bit of storage is sufficient. C is very liberal about the definition of
true. All non-zero values are considered true, and only 0 is considered false. This means that condition checking is based on numerical values rather than on true/false values. It’s important to remember that if an expression is true, its value is 1; if false, its value is 0. Therefore, many expressions are essentially numerical. — C Primer Plus 5th P123
C99 provides astdbool.hfile. Including this header file allows the use ofboolin place of_Bool, withtrueandfalsedefined as symbolic constants with values 1 and 0. Including this header in the program allows writing code that is compatible with C++, as C++ defines bool, true, and false as keywords. — C Primer Plus 5th P125If your system does not support
_Bool, you can useintas a substitute for_Bool. — C Primer Plus 5th P125
The following code is for testing:
1 | // Directly using bool and false is incorrect |
Compiling with gcc (gcc -o testbool testbool.c) will produce the following error:
1 | testbool.c: In function 'main': |
When we include stdbool.h, it will no longer report errors.
1 |
Compile (make sure to add -std=c99), and the result is:
1 | x is false |
Let’s take a look at the code in stdbool.h (in Visual Studio 2015):
1 | // stdbool.h |
The following version is from MinGW’s stdbool.h:
1 | /* Copyright (C) 1998-2015 Free Software Foundation, Inc. |
It can be seen that after including stdbool.h, the bool used is actually of _Bool type, and true and false are also defined as literal constants 1 and 0 by the preprocessor, allowing the use of bool, true, and false keywords, which could be seen as a roundabout way to address the issue :)