Hard
Union type punning vs. std::bit_cast
What does this program print, and is either function's approach undefined behavior?
main.cpp
#include <bit>
#include <cstdint>
#include <iostream>
float bitsToFloatUB(uint32_t bits) {
union U { uint32_t i; float f; };
U u;
u.i = bits;
return u.f; // reading the non-active union member
}
float bitsToFloatWellDefined(uint32_t bits) {
return std::bit_cast<float>(bits);
}
int main() {
uint32_t bits = 0x3F800000; // 1.0f in IEEE-754
std::cout << bitsToFloatUB(bits) << " " << bitsToFloatWellDefined(bits) << std::endl;
}51 of 117 in C++