Search code examples
c++pointersreinterpret-cast

When converting pointers to integers, should I be using reinterpret_cast?


It is my understanding that when converting from a pointer to an integer, I should be using reinterpret_cast because that gives me a compile-time check that the integer variable is large enough to fit a pointer. Is that correct?

As opposed to just casting where I have no guarantuee and could end up truncating addresses when moving from a 32-bit environment to a 64-bit environment?


Solution

  • I should be using reinterpret_cast ... Is that correct?

    Correct... with the precondition that there is a need for such cast in the first place which is rare.

    .. because that gives me a compile-time check that the integer variable is large enough to fit a pointer. Is that correct?

    Not correct. There is no extra guarantee for warnings when compared to c style cast. Reinterpret_cast is preferred because it is more explicit and doesn't allow casting away const.