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 != 0);
}
Although most programming style guides frown on any kind of type punning, this kind of type punning is more dangerous than most. Whereas the former relied only on guarantees made by the C programming language about structure layout and pointer convertibility, this example relies on assumptions about a system's particular hardware. Some situations, such as time-critical code that the compiler otherwise fails to optimize, may require dangerous code. In these cases, documenting all such assumptions in comments helps to keep the code maintainable.
And it also has an example using union. It's worth a read.
-
I was reading the wikipedia article on C++ to see if I'd learn anything. And within two clicks (statically typed -> type punning), I did! =)
I realized the moment I fell into the fissure that the book would not be destroyed as I had planned.
This speaks a lot to portable programming. Depending on one's point of view (or experience), writing code as portable as possible is generally considered "a good thing". I've seen this kind of thing a lot in kernel programming (especially bootstrap code) but it's just as relevant to game programming. I'd like to have my code run on as much hardware as possible to get the most potential for a user base.
Two huge "gotchas" in programming are not checking function return values and assuming too much about cross-platform compatibilities (big endian vs. little endian come to mind).