Search code examples
cstdbool

What does <stdbool.h> do?


What does the <stdbool.h> do when using it in a C code?

I searched for it on the Wikipedia and didn't get answers in my language, i would love that someone will explain to me what it means.


Solution

  • When the C Standard Committee finally added support for a boolean type in the C language in 1999 (C99), they did not want to create incompatible changes in the language semantics, thus they did not make bool, true and false new keywords that would have caused errors in programs already using these identifiers for types or variables, they only added the _Bool keyword for the boolean type, which was already a reserved identifier.

    Yet to make these words available for new programs with standard semantics, they also added a new standard header file <stdbool.h> with this specification:

    7.18 Boolean type and values <stdbool.h>

    1 The header <stdbool.h> defines four macros.

    2 The macro

     bool
    

    expands to _Bool.

    3 The remaining three macros are suitable for use in #if preprocessing directives. They are

     true
    

    which expands to the integer constant ((_Bool)+1u),

     false
    

    which expands to the integer constant ((_Bool)+0u), and

     __bool_true_false_are_defined
    

    which expands to the integer constant 1.

    4 Notwithstanding the provisions of 7.1.3, a program may undefine and perhaps then redefine the macros bool, true, and false.

    I you want to use boolean variables in your program, include the <stdbool.h> header file, declare them with the bool type and use true and false as constant values.


    Note that the phrase macros are suitable for use in #if preprocessing directives is achieved using a trick: true is defined as ((_Bool)+1u), not ((_Bool)1u) so #if true expands to #if ((_Bool)+1u), which ultimately expands to #if ((0)+1u) hence defines a block of source code to be compiled, whereas #if ((0)1u) would have cause a preprocessor error.