I came up with a thought about the types of _Bool
/ bool
(stdbool.h
) in C and bool
in C++.
We use the boolean types to declare objects, that only shall hold the values of 0 or 1. For example:
_Bool bin = 1;
or
bool bin = 1;
(Note: bool
is a macro for _Bool
inside the header file of stdbool.h
.)
in C,
or
bool bin = 1;
in C++.
But are the boolean types of _Bool
and bool
really efficient?
I made a test to determine the size of each object in memory:
For C:
#include <stdio.h>
#include <stdbool.h> // for "bool" macro.
int main()
{
_Bool bin1 = 1;
bool bin2 = 1; // just for the sake of completeness; bool is a macro for _Bool.
printf("the size of bin1 in bytes is: %lu \n",(sizeof(bin1)));
printf("the size of bin2 in bytes is: %lu \n",(sizeof(bin2)));
return 0;
}
Output:
the size of bin1 in bytes is: 1
the size of bin2 in bytes is: 1
For C++:
#include <iostream>
int main()
{
bool bin = 1;
std::cout << "the size of bin in bytes is: " << sizeof(bin);
return 0;
}
Output:
the size of bin in bytes is: 1
So, objects of a boolean type do get stored inside 1 byte (8 bits) in memory, not just in one 1 bit, as it normally only shall require.
The reason why is discussed here: Why is a char and a bool the same size in c++?. This is not what my question is about.
My question are:
Why do we use the types of
_Bool
/bool
(stdbool.h
) in C andbool
in C++, if they do not provide a benefit in memory storage, as it is specificially pretended for use these types?Why can´t I just use the types of
int8_t
orchar
(assumingchar
is contained of 8 bit (which is usually the case) in the specific implementation) instead?
Is it just to provide the obvious impression for a reader of the code, that the respective objects are used for 0
or 1
/true
or false
purposes only?
Thank you very much to participate.