Converting a pointer into an integer

I’d say this is the modern C++ way:

#include <cstdint>
void *p;
auto i = reinterpret_cast<std::uintptr_t>(p);

EDIT:

The correct type to the the Integer

So the right way to store a pointer as an integer is to use the uintptr_t or intptr_t types. (See also in cppreference integer types for C99).

These types are defined in <stdint.h> for C99 and in the namespace std for C++11 in <cstdint> (see integer types for C++).

C++11 (and onwards) Version

#include <cstdint>
std::uintptr_t i;

C++03 Version

extern "C" {
#include <stdint.h>
}

uintptr_t i;

C99 Version

#include <stdint.h>
uintptr_t i;

The correct casting operator

In C there is only one cast and using the C cast in C++ is frowned upon (so don’t use it in C++). In C++ there are different types of casts, but reinterpret_cast is the correct cast for this conversion (see also here).

C++11 Version

auto i = reinterpret_cast<std::uintptr_t>(p);

C++03 Version

uintptr_t i = reinterpret_cast<uintptr_t>(p);

C Version

uintptr_t i = (uintptr_t)p; // C Version

Related Questions

Leave a Comment