Is it safe to cast pointer to integer, increment that integer, and cast back?

541 Views Asked by At

Suppose I have a valid pointer p0:

T a[10];
T* p0 = &a[0];

I know that I can safely round-trip-cast it like this:

reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p0)) == p0;

But is it safe to do the following?

T* p1 = reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p0) + sizeof(T));

i.e. can I be sure that there is no UB and that p1 == &a[1]?

1

There are 1 best solutions below

0
On BEST ANSWER

This is implementation-defined behaviour. Your compiler should document whether or not pointer arithmetic is equivalent to integer arithmetic on the converted numeric values of pointers. That should be the case on modern computers with a "flat" byte-addressed memory space; but it's not guaranteed to work portably on all platforms.

Using char* rather than uintptr_t will work portably, as long as you stay within the array and ensure the pointer is correctly aligned for T before converting back.