Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I convert a null pointer of int to a long type by reinterpret_cast

int *pt = 0;
long i = reinterpret_cast<long>(pt);

Is i guaranteed to be 0? Is this well defined or implementation-defined? I checked the c++ standard, but it only states that

A pointer to a data object or to a function (but not a pointer to member) can be converted to any integer type large enough to contain it.

In this case, pt doesn't point to any data object. Does the rule apply to this case?

like image 651
C-- Avatar asked Apr 12 '11 19:04

C--


1 Answers

No, i is not necessarily any value. The result is implementation-defined.

The representation of pointers, in C++, is implementation-defined, including the representation of a null pointer. When you assign an integer value of zero to a pointer, you set that pointer to the implementation-defined null pointer value, which is not necessarily all-bits-zero. The result of casting that value to an integer is, by transitivity, implementation-defined.

Even more troublesome, though, is that the mapping done by reinterpret_cast is implementation-defined anyway. So even if the null pointer value was all-bits-zero, an implementation is free to make the result whatever it wants. You're only guaranteed that you'll get the original value when you cast back.

That all said, the next sentence after your quote includes the note:

[ Note: It is intended to be unsurprising to those who know the addressing structure of the underlying machine. —end note ]

So even though specific mappings are not required, pragmatically you can take an educated guess.


Assuming long is large enough. In C++0x use uintptr_t, optionally defined in <cstddef>.

like image 131
GManNickG Avatar answered Sep 20 '22 06:09

GManNickG