首页 > float*与int*互转会导致数据不正确,为什么C/C++还允许这么转?有其他什么用途吗?

float*与int*互转会导致数据不正确,为什么C/C++还允许这么转?有其他什么用途吗?

float* 与 int* 互转会导致数据不正确,为什么C/C++还允许这么转?有其他什么用途吗?


我来举一个最经典的例子吧!http://zh.wikipedia.org/zh/%E5%B9%B3%E6%96%B9%E6%A0%B9%E5%80%92%E6%95%B0%E9%80%9F%E7%AE%97%E6%B3%95

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(对浮点数的邪恶位级hack)
    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;
}

反正你可以这么做,于是你就可以作出很多超乎想想的事情~

这里通过过吧float*转成long*,将原浮点数的二进制表示直接与某个数相减来实现一个平方根倒数的估计。


C 允许把你任意类型的指针转成另外的类型,至于得到的数据有没有用那是程序员的事。

就算你规定 float* 不能转成 int*,任何指针必然能和 void* 互转。你的限制有意义么?

一个东西存在不一定非要有用途,也可以是因为功能完整性的原因。底层应该提供机制,而非策略


很多C语言的库都是通过将struct object指针转为void来实现容器的

【热门文章】
【热门文章】