One of my friends asked a question, why is there no Boolean
data type in the C programming language. I did a bit of searching and reading. I got few questions and answers in stack overflow saying that,
We can use a bool in this manner
#define bool int
#define TRUE 1
#define FALSE 0
or use typedef
s.
But my question is this: why wasn't it implemented as a data type in C, even after so many years. doesn't it make sense to implement a one byte data type to store a boolean value rather than using int
or short
explicitly.
C is a very close-to-the-metal language, and abstracting true/false into a new data type that is not reflective of something that hardware can uniquely understand didn't make much sense (a bool would simply be a char with additional limitations, simple enough to typedef yourself if you really need it).
C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.
C99, the version of C released in 1999/2000, introduced a boolean type. To use it, however, you need to import a header file, so I'm not sure we can technically call it “native”. Anyway, we do have a bool type.
Bool or boolean is a primitive data structure that can be used to store only two values i.e. True or False. The size of a boolean data type is 1 byte but it only uses 1 bit of the 8 bits(1 byte = 8 bits) to store the value.
That's not true any more. The built-in boolean type, aka _Bool
is available since C99. If you include stdbool.h
, its alias bool
is also there for you.
_Bool
is a true native type, not an alias of int
. As for its size, the standard only specifies it's large enough to store 0
and 1
. But in practice, most compilers do make its size 1
:
For example, this code snippet on ideone outputs 1
:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool b = true;
printf("size of b: %zu\n", sizeof(b));
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With