zapshe wrote: |
---|
Tested on several compilers and they always converted the value to 0 or 1. |
Converting true to an integer always results in 1.
Converting false to an integer always results in 0.
Converting 0 to a bool always results in false.
Converting a non-zero integer to a bool always results in true.
Assuming normal conversion, implicit or static_cast.
Knowing these things, which I think is reasonable to expect, then your example could have been written more simply as:
1 2 3 4 5 6 7 8
|
#include <iostream>
#include <bitset>
int main()
{
std::cout << std::bitset<8>(1).to_string() << '\n';
std::cout <<"1\n";
}
| |
What I thought you really intended to demonstrate was how the bool was stored (not how the integer value that the bool was converted to was stored). For that you would have to use something like std::bit_cast (requires C++20) to extract the underlying value.
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
#include <bitset>
#include <bit>
#include <cstdint>
int main()
{
bool a = 9;
std::cout << std::bitset<8>(std::bit_cast<std::uint8_t>(a)).to_string() << '\n';
}
| |
https://godbolt.org/z/7TrjjqMPz
zapshe wrote: |
---|
Either way, it would make no sense to store false as anything but 0. You can't even have negatives if its unsigned. |
Perhaps, but it could make some sense to store true as something other than 1. If the compiler allowed multiple representations of true then I think it could implement conversion from integer to bool very cheaply when the integer type is not bigger than sizeof(bool), because it essentially has to do no work at all, it can just use the integer bit pattern as a bool as-is. This might mean it has to do more work elsewhere, e.g. when converting from bool to int, so it might not be worth it but at least it makes some sense.
zapshe wrote: |
---|
That only leaves the question of whether or not the compiler would allow a value over 1. |
You could force other values with std::bit_cast and even if it might not be UB (?) it doesn't seem like a good idea.
Peter87 wrote: |
---|
Question is, what is std::bit_cast<bool>(static_cast<std::uint8_t>(3))? |
zapshe wrote: |
---|
This is also a hacky way to achieve a bool having a value other than 0 or 1. |
Yes, but not as "hacky" as
*((uint8_t*)(&b)) = 3;
which I'm sure could be UB.
I'm not sure if my bit_cast hack is also UB, assuming it compiles, but I suspect it might not be given P2624. How else would you get such values that it talks about?
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2624r0.html