wikipedia
Posted: Fri Oct 09, 2009 10:54 am
So I was browsing around wikipedia, and the article on Type punning has some interesting examples and caveats of those examples.
-
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! =)
And it also has an example using union. It's worth a read.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:Code: Select all
bool is_negative(float x) { return (x < 0.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.Code: Select all
bool is_negative(float x) { unsigned int *ui = (unsigned int *)&x; return (*ui & 0x80000000 != 0); }
-
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! =)