Is using a union for type punning defined behavior in C?
0 upvotes
Practice with AISoon
Yes, in C99 and later. The C standard explicitly allows reading a union member that was not the last one written to. This is commonly used to interpret a float as its raw bit pattern, or to overlay a register value with a struct of named bitfields:
c
union float_bits {float f;uint32_t u;};union float_bits x;x.f = 3.14f;uint32_t raw = x.u; // Defined in C99+
However, this is undefined behavior in C++. If your codebase must compile as both C and C++, use memcpy() instead — the compiler will optimize it to a single register move.
Source: C / C++ Concepts Q&A
