Why doesn't this reinterpret_cast compile?

前端 未结 11 710
暗喜
暗喜 2020-12-04 16:32

I understand that reinterpret_cast is dangerous, I\'m just doing this to test it. I have the following code:

int x = 0;
double y = reinterpret_c         


        
11条回答
  •  醉话见心
    2020-12-04 16:59

    Use a union. It is the least error-prone way to memory map between an integer and a floating point type. Reinterpreting a pointer will cause aliasing warnings.

    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
        union { uint32_t i; float f; } v;  // avoid aliasing rules trouble
        v.i = 42;
        printf("int 42 is float %f\n", v.f);
        v.f = 42.0;
        printf("float 42 is int 0x%08x\n", v.i);
    }
    

提交回复
热议问题