98

What is the C99 _Bool data type and how do you use it?

2 Answers 2

124

Include <stdbool.h> header

#include <stdbool.h>

int main(void){
  bool b = false;
}

Macros true and false expand to 1 and 0 respectively.

Section 7.16 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 1,
    • false: which expands to the integer constant 0, 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.
1
  • 19
    It should also be noted that conversion to _Bool (by assignment, cast, etc.) is effectively by prefixing the expression with !!. Jan 22, 2011 at 13:12
61

Please do check out the answer here on this related thread found on DaniWeb.

extracted and quoted here for convenient reference:-


usage of new keywords in c99

_Bool: C99's boolean type. Using _Bool directly is only recommended if you're maintaining legacy code that already defines macros for bool, true, or false. Otherwise, those macros are standardized in the <stdbool.h> header. Include that header and you can use bool just like you would in C++.

#include <stdio.h>
#include <stdbool.h>

int main ( void )
{
  bool b = true;

  if ( b )
    printf ( "Yes\n" );
  else
    printf ( "No\n" );

  return 0;
}

1
  • 22
    +1 for explanation of why _Bool exists along with bool. Very helpful to understand it.
    – eonil
    Nov 17, 2014 at 23:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.