I can't find an answer in the standard documentation. Does the C++ language standard require sizeof(bool)
to always be 1 (for 1 byte), or is this size implementation-defined?
4 Answers
sizeof(bool)
is implementation defined, and the standard puts notable emphasis on this fact.
§5.3.3/1, abridged:
sizeof(char)
,sizeof(signed char)
andsizeof(unsigned char)
are 1; the result ofsizeof
applied to any other fundamental type is implementation-defined. [Note: in particular,sizeof(bool)
andsizeof(wchar_t)
are implementation-defined.69)]
Footnote 69):
sizeof(bool)
is not required to be 1.
-
is there a flag that i need to compile my program with, that my compiler will use only 1 byte for
bool
?– EagleCommented May 30, 2011 at 9:29 -
3@Eagle: That's up to your compiler, I'm not sure. It's probably best you left it up to your compiler. Commented May 30, 2011 at 10:02
-
9note that std::vector<bool> is optimized to a vector containing 1bit bools by the standard. Commented Feb 10, 2016 at 16:40
-
-
@user3063349 is it standard really? This mentions implementation-dependence Commented Jan 7, 2022 at 7:57
http://msdn.microsoft.com/en-us/library/tf4dy80a.aspx
"In Visual C++4.2, the Standard C++ header files contained a typedef that equated bool with int. In Visual C++ 5.0 and later, bool is implemented as a built-in type with a size of 1 byte. That means that for Visual C++ 4.2, a call of sizeof(bool) yields 4, while in Visual C++ 5.0 and later, the same call yields 1. This can cause memory corruption problems if you have defined structure members of type bool in Visual C++ 4.2 and are mixing object files (OBJ) and/or DLLs built with the 4.2 and 5.0 or later compilers."
-
2You do realize that this is somewhat related to the question, but clearly not an answer, since 0xbadf00d asked about the standard, not some specific/arbitrarily selected compiler implementation, right? Commented Dec 12, 2013 at 22:27
-
16
-
19@kinokijuf It's not a counterexample. There are many things in Visual C++ that are not standard-compliant. Commented May 13, 2016 at 15:43
It's implementation defined. Only sizeof(char)
is 1
by the standard.
-
3pls note that the 1 in the standard can mean 4 byte. Than every type is a product of 4. So care that the standard ONLY defines char is the 1, but not defines the measurment. Commented Feb 10, 2016 at 16:39
-
1
-
191 byte. The number of bits per byte is not defined by the standard (it needs to be at least 8 IIRC), but can be found in
CHAR_BIT
, defined inclimits
.– peoroCommented Jul 2, 2016 at 2:13 -
sizeof(unsigned char)
andsizeof(signed char)
also have to be1
by the standard– marbensCommented Jan 13 at 18:50
See 5.3.3 paragraph 1 :
[Note: in particular, sizeof(bool) and sizeof(wchar_t) are implementation-defined.69) ]
bool
to be 1 byte, you can check it at compile-time:static_assert(sizeof(bool) == 1, "OMG bool is big here");
.