Boolean in C
In C, the bool data type is not a built-in data type. However, the C99 standard for C language supports bool variables. Boolean can store values as true-false, 0-1, or can be yes-no. It can be implemented in C using different methods as mentioned below:
- Using header file “stdbool.h”
- Using Enumeration type
- Using define to declare boolean values
1. Using Header File “stdbool.h”
To use bool in C, you must include the header file “stdbool.h”. After including the stdbool.h library we can use the data type as boolean is not available with stdio.h library.
Below is the implementation of the boolean in C:
C
// C Program to implement // Boolean data type #include <stdbool.h> // Main Function int main() { // Boolean data types declared bool a = true ; bool b = false ; printf ( "True : %d\n" , a); printf ( "False : %d" , b); return 0; } |
True : 1 False : 0
If we save the above program as a .c file, it will not compile. But if we save it as a .cpp file, it will work fine.
2. Using the Enumeration Type
Alternatively, you can implement bool in C using an enumeration type. Here rather than importing the library, we declare an enumeration type so as to use bool as the data type.
Below is an example of using an enumeration-type approach:
C
#include <stdio.h> typedef enum { false , true } bool ; int main() { bool a = true ; bool b = false ; printf ( "True : %d\n" , a); printf ( "False : %d" , b); return 0; } |
True : 1 False : 0
3. Using Define to Declare Boolean Values
In this case, the false value is assigned the integer value of 0, and the true value is assigned the integer value of 1. You can also use an int or a char with a value of either 0 (false) or 1 (true) to represent the bool data type in C.
Below is the implementation of the above approach:
C
#define bool int #define false 0 #define true 1 int main() { bool a = true ; bool b = false ; printf ( "True : %d\n" , a); printf ( "False : %d" , b); return 0; } |
True : 1 False : 0
bool in C
The bool in C is a fundamental data type in most that can hold one of two values: true or false. It is used to represent logical values and is commonly used in programming to control the flow of execution in decision-making statements such as if-else statements, while loops, and for loops. In this article, we will explore how to use the bool data type in C.