Use of Bool in C

Bool in C

 

In this section we will discuss the use of bool in the C programming language.

The C programming language, as of C99, supports the use of boolean with the help of built-in -type _Bool. bool can be used in place of _Bool if stdbool.h header file is included.

_Bool

_Bool is data type which was introduced in C99. the variables of _Bool only holds two value 0(false) and 1(true). When storing value in the _Bool data type 0 is stored when the input is 0 and for every other input 1 is stored. For example say we have input 2019 then 1 will be stored.

use of bool in c

Example:

#include
int main()
{
    _Bool check =    2019;
    printf("the output is %d",check);
    return 0;
}

Output

the output is 1

As we can see even when the input is 2019 the output is 1.

 We have another way of using boolean arithmetic in C Programming language which by using bool which is a macros in the stdbool.h header. 

stdbool.h

There are 4 macros in the header stdbool.h in the C Standard Library for the C programming language for a Boolean data type. This header was introduced in C99.

The macros as defined in the ISO C standard are :

  • bool which expands to _Bool
  • true which expands to 1
  • false which expands to 0
  • __bool_true_false_are_defined which expands to 1  

Example:

#include <stdio.h>
#include <stdbool.h>
int main()
{
    bool x=true,y=false;
    printf("the value of x: %d",x );
    printf("\nthe value of y: %d",y );
    return 0;
}

Output:

the value of x: 1
the value of y: 0