Reputation: 4367
Let us say I have the following code:
Foo *foo = something();
uintptr_t bar = reinterpret_cast<uintptr_t>(foo);
Does bar
represent the address of foo
or the address that foo
points to? I believe it's the address of foo
, but I want to be certain that I am not mistaken.
Some clarification
What is uintptr_t data type explains that
In C99, it is defined as "an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer".
But this doesn't state what is being stored. Could the compiler conceivably store the address that foo
points to in bar
instead and then construct a new pointer with a different address when casting back to Foo
from uintptr_t
? Perhaps I'm misunderstanding pointer comparisons, but since they point to the same object, will they not compare equal?
I guess I'm looking for some pedantic clarity about about if I add the following line:
Foo *foo2 = reinterpret_cast<Foo *>(bar);
What on earth happens here? Undefined behavior? foo2
just points to the same object as foo
?
Upvotes: 2
Views: 2092
Reputation: 136256
It depends on what the cast is applied to.
In uintptr_t bar = (uintptr_t)foo;
it stores the value of foo
(the address of pointed to object) in bar
.
Prefer using C++ casts, they convey more information to the reader and are more robust during maintenance - the best practice:
uintptr_t bar = reinterpret_cast<uintptr_t>(foo);
Upvotes: 3
Reputation: 21917
It's an integral value that represents the address that foo
points to.
If you were to write it as
uintptr_t bar = (uintptr_t)(&foo);
Then it would be the address of foo
itself.
Upvotes: 2