Why is a char and a bool the same size in c++?
I'm reading The C++ Programming Language. In it Stroustrup states that sizeof(char) == 1
and 1 <= sizeof(bool)
. The specifics depend on the implementation. Why would such a simple value as a boolean take the same space as a char?
Solution 1:
In modern computer architectures, a byte is the smallest addressable unit of memory. To pack multiple bits into a byte requires applying extra bit-shift operations. At the compiler level, it's a trade off of memory vs. speed requirements (and in high-performance software, those extra bit-shift operations can add up and slow down the application needlessly).
Solution 2:
Because in C++ you can take the address of a boolean and most machines cannot address individual bits.