In a Wikipedia article on type punning it gives an example of pointing an int type pointer at a float to extract the signed bit:
However, supposing that floating-point comparisons are expensive, and also supposing that float is represented according to the IEEE floating-point standard, and integers are 32 bits wide, we could engage in type punning to extract the sign bit of the floating-point number using only integer operations:
bool is_negative(float x) { unsigned int *ui = (unsigned int *)&x; return *ui & 0x80000000; }
Is it true that pointing a pointer to a type not its own is undefined behavior? The article makes it seem as if this operation is a legitimate and common thing. What are the things that can possibly go wrong in this particular piece of code? I'm interested in both C and C++, if it makes any difference. Both have the strict aliasing rule, right?