in reality, in C we don’t have a Boolean data type but some languages do have such as java, C++, and visual basic
Is it possible to use bool in C?
Yes! Absolutely
But we need to create our own Boolean type
So, here are the six ways by which we can create a bool in C
- Use #include<stdbool.h> to use keyword bool
- Use _Bool an unsigned integer
- Create pre-processor macros
- Create global variables
- Define a bool type by using typedef
- Define a bool type by using an Enum
Use #include<stdbool.h> to use keyword bool
#include <stdio.h>
#include<stdbool.h>
int main()
{
bool x,y;
int a=50,b=60,c=70;
x=a<b;//50<60 is true
y=b>=c;//60>=70 is false
printf("%d\n%d",x,y);// error if you didn’t include<stdbool.h>
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 _Bool an unsigned integer
The difference between using #include<stdbool.h> and _Bool is that the _Bool unsigned integer does not define constants true as 1 and false as 0
#include <stdio.h>
//#include<stdbool.h>
int main()
{
_Bool x,y;
int a=50,b=60,c=70;
x=a<b;//50<60 is true
y=b>=c;//60>=70 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
Create pre-processor macros
#include <stdio.h>
# define true 1 //pre-processor macros
# define false 0 //pre-processor macros
int main()
{
int a=50,b=60;
if ((a<b)==0)
printf("%d",true);
else
printf("%d",false);
return 0;
}
Output
0
Create global variables
#include <stdio.h>
const int true= 1; //global variable
const int false= 0; //global variable
int main()
{
int a=50,b=60;
if ((a<b)==0)
printf("%d",true);
else
printf("%d",false);
return 0;
}
Output
0
Define a bool type by using typedef
#include <stdio.h>
int main()
{
typedef int boolean;
boolean true=1;
boolean false=0;
int a=50,b=60;
if ((a<b)==0)
printf("%d",true);
else
printf("%d",false);
return 0;
}
Output
0
Define a bool type by using an Enum
#include <stdio.h>
enum boolean{true=1,false=(!true)};
int main()
{
enum boolean;
int a=50,b=60;
if ((a<b)==0)
printf("%d",true);
else
printf("%d",false);
return 0;
}
Output
0
Leave a Reply