The keyword _Bool
in C is used to represent the built-in boolean data type. _Bool
is an unsigned integer type in which 0 represents false and 1 represents true.
In C, _Bool
can be declared as:
_Bool foo = 0;
OR:
_Bool foo = 1;
Consider the code snippet below, which shows the use of _Bool
:
#include<stdio.h>int main() {_Bool foo = 1;if(foo){// same as if(foo == 1)printf("Boolean is true");}else if(!foo){// same as if(foo == 0)printf("Boolean is false");}return 0;}
If _Bool
is declared with a value greater than 1, it stores the number as 1:
#include<stdio.h>int main() {_Bool foo = 8;if(foo == 1){printf("Boolean is true \n");printf("Boolean value: %d \n", foo);}else if(foo == 0){printf("Boolean is false \n");}return 0;}
When assigned a pointer, _Bool
stores 1 if the pointer points to something and stores 0 if the pointer is NULL:
#include<stdio.h>int main() {int a = 10;int * ptr = NULL;_Bool foo1 = ptr;if(foo1 == 1){printf("Boolean is true \n");}else if(foo1 == 0){printf("Boolean is false \n");}ptr = &a;_Bool foo2 = ptr;if(foo2 == 1){printf("Boolean is true \n");}else if(foo2 == 0){printf("Boolean is false \n");}return 0;}
Free Resources