How do C/C++ compilers handle type casting between types with different value ranges?

前端 未结 4 543
情话喂你
情话喂你 2020-12-08 23:07

How do type casting happen without loss of data inside the compiler?

For example:

 int i = 10;
 UINT k = (UINT) k;

 float fl = 10.123;
 UINT  ufl =          


        
4条回答
  •  星月不相逢
    2020-12-08 23:39

    The two C-style casts in your example are different kinds of cast. In C++, you'd normally write them

    unsigned int uf1 = static_cast(fl);
    

    and

    unsigned char* up = reinterpret_cast(p);
    

    The first performs an arithmetic cast, which truncates the floating point number, so there is data loss.

    The second makes no changes to data - it just instructs the compiler to treat the pointer as a different type. Care needs to be taken with this kind of cast: it can be very dangerous.

提交回复
热议问题