union foo {
int x;
float y;
};
union foo bad;
bad.x = 100;
printf("%f\n", bad.y); // undefined behavior (though usually works) union foo {
int x;
float y;
};
union foo bad;
bad.x = 100;
printf("%f\n", bad.y); // undefined behavior (though usually works)[1]: http://dbp-consulting.com/tutorials/StrictAliasing.html
> If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called ‘‘type punning’’). This might be a trap representation
float half_r=r*0.5F;
union
{
float y;
int32_t i;
};
y=r;
i=0x5f375a86-(i>>1);
y=y*(1.5F-(half_r*y*y));
return y;But where I'd more likely use that optimization at this point is on Arm or ATmega processors. ARM doesn't seem to have an approximate inverse square root, based on a quick check, and ATmega are frequently still stuck with software floating point, so I'd hardly say that the optimization is dead.
fn approx_invsqrt(r : f32) -> f32
{
let y : f32 = unsafe {
let i : i32 = std::mem::transmute(r);
std::mem::transmute(0x5f375a86 - (i>>1))
};
return y*(1.5-(0.5*r*y*y));
}
fn main()
{
println!("approx_invsqrt(2.0) = {}", approx_invsqrt(2.0));
}
Result: approx_invsqrt(2.0) = 0.70693