#include
#include
using namespace std;
int main()
{
bool a = 0x03;
bitset<8> x(a);
cout<
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
.