C Boolean in C language
Categories: C language
In C, Boolean is a data type that contains two types of values, i.e., 0 and 1. Basically, the bool type value represents two types of behavior, either true or false. Here, '0' represents false value, while '1' represents true value.
In C Boolean, '0' is stored as 0, and another integer is stored as 1. We do not require to use any header file to use the Boolean data type in C++, but in C, we have to use the header file, i.e., stdbool.h. If we do not use the header file, then the program will not compile.
Syntax
bool variable_name;
In the above syntax, bool is the data type of the variable, and variable_name is the name of the variable.
In the above code, we have used <stdbool.h> header file so that we can use the bool type variable in our program. After the declaration of the header file, we create the bool type variable 'x' and assigns a 'false' value to it. Then, we add the conditional statements, i.e., if..else, to determine whether the value of 'x' is true or not.
Output
The value of x is FALSE
Boolean Array
Now, we create a bool type array. The Boolean array can contain either true or false value, and the values of the array can be accessed with the help of indexing.
Let's understand this scenario through an example.
#include <stdio.h>
#include<stdbool.h>
int main()
{
bool b[2]={true,false}; // Boolean type array
for(int i=0;i<2;i++) // for loop
{
printf("%d,",b[i]); // printf statement
}
return 0;
}
In the above code, we have declared a Boolean type array containing two values, i.e., true and false.
Output
1,0,
typedef
There is another way of using Boolean value, i.e., typedef. Basically, typedef is a keyword in C language, which is used to assign the name to the already existing datatype.
In the above code, we use the Boolean values, i.e., true and false, but we have not used the bool type. We use the Boolean values by creating a new name of the 'bool' type. In order to achieve this, the typedef keyword is used in the program.
typedef enum{false,true} b;
The above statement creates a new name for the 'bool' type, i.e., 'b' as 'b' can contain either true or false value. We use the 'b' type in our program and create the 'x' variable of type 'b'.