May one convert a char with the value not \0 and not \1 into bool using std::bit_cast? And if yes, what will the value of the resulting bool: true or false?
For example,
#include <bit>
constexpr bool x = [] {
return std::bit_cast<bool>('\2');
}();
int main() {
return x;
}
This program returns 2 in EDG and MSVC, 0 in GCC. And only Clang rejects it with the error:
<source>:3:16: error: constexpr variable 'x' must be initialized by a constant expression
/opt/compiler-explorer/clang-20.1.0/bin/../include/c++/v1/__bit/bit_cast.h:37:10: note: value 2 cannot be represented in type 'bool'
Online demo: https://gcc.godbolt.org/z/P6xPPn5Ez
Which implementation is correct here?
std::bit_cast<bool>on a value whose bit pattern doesn't correspond to the bit pattern of a validboolvalue is undefined. The C++ standard doesn't impose any requirement on what the code in the question does.0is interpreted as false How much of that historic code usesstd::bit_cast?return std::bit_cast<bool>('\2');withreturn '\2' != '\0';static_cast. I sometimes use double-bang (!!) for fun and succinctness, but it's not good, and may fail, in case of any inconsistencies in the input type's interface.bit_casthas UB in cases where the source bit pattern doesn't have defined meaning in destination type.boolhas only two values, with platform dependent bit patterns. So, technicallybit_cast<bool>is almost always UB, unless fromenum :booltypes in which case the affirmationedstatic_castis preferred.