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,
- All data types should be addressable, and a bit cannot be addressed.
- 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.
<stdbool.h><stdbool.h>but that uses integer as a return type. why integer, wont 4 bytes be redundant (considering sizeof(int) = 4), if we can do that using just 1 bytesizeof(bool)depends on the implementation, but if you're in C99 mode,sizeof(bool)is typically equal to1. I answered a similar question long ago: stackoverflow.com/a/10630231/297696. Older implementations may keepsizeof(bool) == sizeof(int)(or whatever) for compatibility reasons.bool b = (x & 0x8000);. Ifboolis an alias forcharthen this will set it tofalseeven if the intended bit is set. This problem is more insidious for a function that takes bool as parameter, or returns bool.