Sitemap
Kiran Chauhan

Kiran Chauhan

I design software with and for people.

Boolean Data Type in C

2 min readJan 26, 2022

bool data type or keyword is used to define a Boolean variable with initial value of true or false. For example,

bool x = false;
bool y = true;

But, by default this doesn’t work. We need to include stdbool.h header file in program to make this working as bool, true, and false are defined in this stdbool.h file.

Putting all these together, here is the simple program that print hello, world twice.

#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool x = false;
bool y = true;
if (!x) {
printf("hello, world\n");
}

if (y) {
printf("hello, world\n");
}
return 0;
}

In C, 0 means false and other value than 0 means true. If you take a look at the code written inside the stdbool.h, you’ll find that true and false has 1 and 0 value respectively.

#define bool        _Bool
#define true 1
#define false 0

That is the reason above condition evaluated as we expected e.g. !x as true and also y as true.

Get Kiran Chauhan’s stories in your inbox

Join Medium for free to get updates from this writer.

Finally, there is no format specifier for Boolean to print true or false in printf() function. You need to use int in such a case.

#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool x = false;
bool y = true;
if (!x) {
printf("hello, world\n");
printf("The value of x is %d\n", x);
}

if (y) {
printf("hello, world\n");
printf("The value of y is %d\n", y);
}
return 0;
}

If you insist more on printing true and false then we can use trick like x ? “true” : “false” and then use %s as format specifier.

#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool x = false;
bool y = true;
if (!x) {
printf("hello, world\n");
printf("The value of x is %s\n", x ? "true" : "false");
}

if (y) {
printf("hello, world\n");
printf("The value of y is %s\n", y ? "true" : "false");
}
return 0;
}

--

--

Kiran Chauhan
Kiran Chauhan

Written by Kiran Chauhan

I design software with and for people.