From what I understood about strict aliasing rule, this code for fast inverse square root will result in undefined behavior in C++:
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // type punning
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) );
return y;
}
Does this code indeed cause UB? If yes, how can it be reimplemented in standard compliant way? If not, why not?
Assumptions: before calling this function we have somehow checked that floats are in IEEE 754 32-bit format, sizeof(long)==sizeof(float)
and the platform is little-endian.