Wishbone: Then of course there's code that's not bad as such, in fact it's so good it's almost magical, but quite unintuitive and extremely difficult to understand. Example:
The fast inverse square root algorithm.
For those unfamiliar with it, calculating the inverse square root of a floating point number is an important part of lighting and reflection calculations used in 3D graphics. As such, it is quite important that this can be done very very quickly. The algorithm has been wrongly attributed to John Carmack, because is was used in Quake III Arena, but Carmack only used it, he didn't invent it.
For your enjoyment, here is the code of the function used in Quake III Arena:
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the fuck?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
Wishbone: Edit:
The GOG forum does not like whitespaces. I really wish we could use code tags here. For a properly formatted version of the code, see the Wikipedia page linked at the top of this post.
It's interesting to note that the language Rust has an explicit way to do what he is doing. In Rust, the code would look something like this:
fn Q_rsqrt(number: f32) -> f32 {
let threehalves = 1.5; //const is the default in Rust
let x2 = number * 0.5f32;
let mut y = x; // Notice the "mut" keyword here
let mut i : i32 = unsafe { mem::transmute(y) }; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the fuck?
y = unsafe { mem::transmute(i) };
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
y
}
What do you think of how the code looks in Rust? (Note that mem::transmute doesn't convert the value; it effectively does nothing, just like the weird typecast of the C version, but no pointers are needed here.)
Edit: Made one correction, should be transmuting i, not y, for the second transmute.