Why the Sizeof(Bool) Is Not Defined to Be One, by the Standard Itself

Why the sizeof(bool) is not defined to be one, by the Standard itself?

Many platforms cannot effectively load values smaller than 32 bits. They have to load 32 bits, and use a shift-and-mask operation to extract 8 bits. You wouldn't want this for single bools, but it's OK for strings.

Is sizeof(bool) defined in the C++ language standard?

sizeof(bool) is implementation defined, and the standard puts notable emphasis on this fact.

§5.3.3/1, abridged:

sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1; the result of sizeof applied to any other fundamental type is implementation-defined. [Note: in particular, sizeof(bool) and sizeof(wchar_t) are implementation-defined.69)]

Footnote 69):

sizeof(bool) is not required to be 1.

Why is a boolean 1 byte and not 1 bit of size?

Because the CPU can't address anything smaller than a byte.

Why is there assert( sizeof( bool ) == 1 ) in Doom 3 source?

Some platforms define bool to be the same size as int. At least older versions of Mac OS X (and likely other RISC BSD ports) were like this. Presumably the code uses bool arrays with an assumption of efficiency. Doom has been ported to a lot of platforms so it's probably very cagey about such things.

It has to be done at runtime because there is no standard macro specifying sizeof(bool), and compile time checks didn't work with non-macro expressions until C++11.

sizeof(bool) g++ vs vc++

There are versions of g++ (and versions of Visual C++ as well for that matter) for which on some platforms sizeof(bool) is not equal to 1. So no, you can't assume that it will be the same on g++ and Visual C++. You can't even assume that it's the same on different versions of the same compiler or the same version on different platforms.

Why the sizeof(bool) is not defined to be one, by the Standard itself?

Many platforms cannot effectively load values smaller than 32 bits. They have to load 32 bits, and use a shift-and-mask operation to extract 8 bits. You wouldn't want this for single bools, but it's OK for strings.

Why is a char and a bool the same size in c++?

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



Related Topics



Leave a reply



Submit