Is it safe to cast an int to void pointer and back to int again?

前端 未结 8 1904
失恋的感觉
失恋的感觉 2020-12-06 18:18

In C and/or C++: is it safe to cast an int to void pointer and back to int again?

Based on the question \"C++: Is it safe to cast pointer to int and later back to po

8条回答
  •  天命终不由人
    2020-12-06 19:11

    If the range of your integers is fairly small, you could always do something like:

    static const char dummy[MAXVAL];
    

    and then use dummy+i as a way of encoding i as a pointer. This is 100% portable. If you only care that it's 99% portable, you could use (char *)0 + i.

提交回复
热议问题