Is it safe to cast pointer to int and later back to pointer again?
How about if we know if the pointer is 32 bit long and int is 32 bit long?
long* juggle(long* p) { static_assert(sizeof(long*) == sizeof(int)); int v = reinterpret_cast<int>(p); // or if sizeof(*)==8 choose long here do_some_math(v); // prevent compiler from optimizing return reinterpret_cast<long*>(v); } int main() { long* stuff = new long(42); long* ffuts = juggle(stuff); std::cout << "Is this always 42? " << *ffuts << std::endl; }
Is this covered by the Standard?
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.
A cast does not change the value of an object. While technically correct, your answer is misleading. Casting a pointer to a class instance may return a different pointer address than the casted pointer contains.
A pointer is an arrow that points to an address in memory, with a label indicating the type of the value. The address indicates where to look and the type indicates what to take. Casting the pointer changes the label on the arrow but not where the arrow points.
No, it is no valid to assign a pointer to an integer. It's a constraint violation of the assignment operator (C99, 6.5. 16.1p1).
No.
For instance, on x86-64, a pointer is 64-bit long, but int
is only 32-bit long. Casting a pointer to int and back again makes the upper 32-bit of the pointer value lost.
You may use the intptr_t
type in <cstdint>
if you want an integer type which is guaranteed to be as long as the pointer. You could safely reinterpret_cast from a pointer to an intptr_t
and back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With