Search code examples
c++pointersintegerc++17reinterpret-cast

Casting an arbitrary integer to void*


Recently I encountered code that did this:

static_assert(sizeof(void*) >= sizeof(size_t));

size_t idx = get_index_to_array();
void* ptr = (void*)idx;

Essentially using a void* pointer provided by a third party library to store an index into an array to save an allocation.

Assuming that the pointer will neither be dereferenced nor freed/deleted at any point, and will be only used to cast back to the original value, is this code strictly conforming C++ (per the C++17 standard, if that matters)?


Solution

  • Asuming that the pointer will not get dereferenced nor freed/deleted at any point and will be only used to cast back to the original value, is this code strictly conforming C++ (per the C++17 standard, if that matters)?

    It is conforming.

    Since there is no compatible static cast, this explicit type conversion (colloquially called C-style cast) performs a reinterpret cast. Of this, the standard says (quoting the latest draft):

    [expr.reinterpret.cast]

    A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined.