_Bool in C
Do not miss this exclusive book on Binary Tree Problems. Get it now for free.
Reading time: 20 minutes | Coding time: 5 minutes
_bool is a keyword in C Programming language representing boolean data type. It is an alternative to bool in C. In fact, bool is an alias to _bool. This was done considering the historic usage of C as an attempt to maintain compatibility.
As _bool is a keyword, you need not include any header file to use it. For using bool, you need to include stdbool.h header file as:
#include <stdbool.h>
Example of using _bool:
#include <stdio.h>
int main()
{
_Bool data = 1;
printf("%d", data);
return 0;
}
In fact, we can assign any integer value to data. If the integer is any integer other than 0, it is considered as 1 that is true. 0 is considered as false.
In this example, we will assign value 5 to _Bool and print the value. Note that 1 will be printed instead of 5.
#include <stdio.h>
int main()
{
_Bool data = 5;
printf("%d", data);
return 0;
}
Output:
1
If we use 0, 0 will be printed.
#include <stdio.h>
int main()
{
_Bool data = 0;
printf("%d", data);
return 0;
}
0
Now, bool is an alias to _Bool. To use bool, we need to include the header file stdbool.h.
Consider this example in which we use bool but do not include the header file. It will give compile time error:
#include <stdio.h>
int main()
{
bool data = 1;
printf("%d", data);
return 0;
}
Compile time error:
opengenus.c: In function 'main':
opengenus.c:5:2: error: unknown type name 'bool'
bool data = 1;
^
If we include the header file, it will run correctly. Following is the correct C code:
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool data = 1;
printf("%d", data);
return 0;
}
History behind _Bool
Initially, C programming language did not support boolean as a data type. In version C99, C developers decided to add a new keyword to add native support for boolean.
The problem was that a lot of programmers have worked around the limitation of C by creating their own boolean data type. C at that time was the only major programming languages and had wide adaptation.
If C had added a new keyword/ datatype, it might break existing code which may be using the same keyword (like bool). To prevent this, C designers made the decision to include the new keyword as _Bool.
In programming design, it is widely accepted that using underscore infront of a keyword means that the variable is an internal variable and should not be used or changed.
Hence, C introduced _Bool as a keyword for boolean and at the same time, introduced the header file stdbool.h.
stdbool.h defines:
- bool as an alias to _Bool
- true as an alias to 1
- false as an alias to 0
Using stdbool.h means that you are agree that the introduction of bool will not break your code.
For a programming language like C, it takes significant time (over a decade) to bring in breaking changes.
Hence, you can chose between using bool or _Bool in your program.
Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.