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

前端 未结 4 537
情话喂你
情话喂你 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:42

    Casts mean different things depending on what they are. They can just be renamings of a data type, with no change in the bits represented (most casts between integral types and pointers are like this), or conversions that don't even preserve length (such as between double and int on most compilers). In many cases, the meaning of a cast is simply unspecified, meaning the compiler has to do something reasonable but doesn't have to document exactly what.

    A cast doesn't even need to result in a usable value. Something like char * cp; float * fp; cp = malloc(100); fp = (float *)(cp + 1); will almost certainly result in a misaligned pointer to float, which will crash the program on some systems if the program attempts to use it.

提交回复
热议问题