Casting twice in the same line

后端 未结 3 834
广开言路
广开言路 2021-02-07 12:19

I saw this code in project.

b\'s type is void*:

void *b = ...;
int a = (int) (unsigned long) b;

Is this line

3条回答
  •  心在旅途
    2021-02-07 12:42

    Directly typecasting to pointer to smaller type say int may result in compilation error on some compiler (like Clang) under x64 bit environment.

    For example:

     void *p = GetSomeAddress;
     int i = (int)p;  //error on compilers like Clang.
    

    Solution is:

    int i = (int)(unsigned long)p;
    

    or

    int i = (int)(long)p;
    

    This is because, on Unix, under LP64 model, long is 64-bit.

    Such cases, you need to look thoroughly that why you need typecast from pointer to int or other smaller type which can result in loss of the data.

    This question may also help you. How should I handle "cast from ‘void*’ to ‘int’ loses precision" when compiling 32-bit code on 64-bit machine?

提交回复
热议问题