The reason it's undefined is because there's no guarantee what exactly the value representations of int
and float
are. The C++ standard doesn't say that a float
is stored as an IEEE 754 single-precision floating point number. What exactly should the standard say about you treating an int
object with value 0xffff
as a float
? It doesn't say anything other than the fact it is undefined.
Practically, however, this is the purpose of reinterpret_cast
- to tell the compiler to ignore everything it knows about the types of objects and trust you that this int
is actually a float
. It's almost always used for machine-specific bit-level jiggery-pokery. The C++ standard just doesn't guarantee you anything once you do it. At that point, it's up to you to understand exactly what your compiler and machine do in this situation.
This is true for both the union
and reinterpret_cast
approaches. I suggest that reinterpret_cast
is "better" for this task, since it makes the intent clearer. However, keeping your code well-defined is always the best approach.