Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why was the boolean data type not implemented in C

Tags:

c

boolean

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,

  1. All data types should be addressable, and a bit cannot be addressed.
  2. The basic data structure at the hardware level of mainstream CPUs is a byte. Operating on bits in these CPUs require additional processing.

We can use a bool in this manner

#define bool int
#define TRUE 1
#define FALSE 0

or use typedefs.

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.

like image 911
Haris Avatar asked Sep 22 '14 12:09

Haris


People also ask

Why is there no boolean in C?

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).

Does Boolean data type exist in C?

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.

When did C get bool?

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.

Is boolean a primitive data type in C?

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.


1 Answers

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;
}
like image 116
Yu Hao Avatar answered Oct 05 '22 17:10

Yu Hao