#include
#include
using namespace std;
int main()
{
bool a = 0x03;
bitset<8> x(a);
cout<
C++11, §3.9.1/6:
Values of type bool are either true or false. [...]
Why would you even think you could?
It's like saying int i = "abc";
.
The only values you can legitimately store in a bool
object are false
and true
. All conversions from other types to bool
yield one of those two values. A bool
object is always at least 8 bits in size (unless it's a bit field), but the language deliberately makes it difficult to store any of the other 254 (or more) possible values.
You can play tricks, like using memcpy
, or using a union, or using pointer conversions, to store any other value that will fit. But if you do so, it probably makes your program's behavior undefined. What that means is that the compiler is permitted to generate code that assumes the stored value is either false
or true
(or 0
or 1
). Store something else, and your program's behavior is unpredictable.
bool
is at least 8 bits because the C++ memory model doesn't deal well with sub-byte objects (other than bit fields). You're not supposed to use those other 7 (or more) bits.
If you want to store more than 2 values in an object, don't make it a bool
.
A bool
can only hold two values: false
and true
.
When/if used in an integer context, a bool
can be converted to an int
. In this case, false
converts to 0
and true
converts to 1
.
Regardless of the size of storage used for a bool
(e.g., sizeof(bool)==1
and sizeof(bool)==4
are both fairly common) it can still only hold the two values false
and true
, which always convert to 0
and 1
respectively. No other value is possible.
§4.12 Boolean conversions [conv.bool]
1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
bool a = 0x03;
converts 0x03 to a boolean value. Since every numeric value that is not zero will be evaluated to be true, you'll see the first result, regardless of which data you'll assign.