But why the compiler throws an error?
because you didn’t include the library #include<stdbool.h>
in C we don’t have a bool data type as we have in other languages such as C++, Python, and Java
so far, clear as mud?
Then, what we can do?
In general, we can define our Boolean type
So, here are Six ways by which we can use bool in C
- First, use bool by using #include <stdbool.h>
- Second, use directly_Bool unsigned integer
- Third create them by using pre-processor macros[# define true 1 and # define false 0]
- Fourth create global variable[int true=1; int false=0]
- Fifth: define Boolean type by using a simple typedef[ typedef int BOOLEAN;]
- Sixth:define Boolean type by using Enum[enum Boolean{true=1,fasle=0};
Click here to see how we can implement the above 6 ways
Bool by using #include<stdbool.h>
The bool data type can take two values that is true(1) and false(0) which is commonly used for comparisons
in the first place, we can use bool by including a file called #include<stdbool.h> which also defines constants true as 1 and false as 0
#include <stdio.h>
#include<stdbool.h>
int main()
{
bool x,y;
int a=10,b=20,c=30;
x=a<b;//10<20 is true
y=b>=c;//20>=30 is false
printf("%d\n%d",x,y);
printf("\nvalue=%d,value=%d",true,false);// error if you didn’t include<stdbool.h>
return 0;
}
Output
1
0
value =1, value=0
use directly_Bool unsigned integer
in short, we can use integers for Boolean testing ( _Bool is an unsigned integer for which we can assign 0 or 1)
to point out, _Bool does not define constants “true” and “false”, with 1 and 0
#include <stdio.h>
//#include<stdbool.h>
int main()
{
_Bool x,y;
int a=10,b=20,c=30;
x=a<b;//10<20 is true
y=b>=c;//20>=30 is false
printf("%d\n%d",x,y);
//printf("value =%d,value=%d",true,false);// error if you didn’t include<stdbool.h>
return 0;
}
Output
1
0
to clarify, in C++ we don’t need any header file to include
#include <iostream>
using namespace std;
int main()
{
bool x,y;
int a=10,b=20,c=30;
x=a<b;//10<20 is true
y=b>=c;//20>=30 is false
cout<<endl<<x<<endl<<y;
cout<<endl<<"value="<<true<<endl<<"value="<<false;
return 0;
}
Output
1
0
value=1
value=0
Leave a Reply