Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

reinterpret_cast — low-level type casting

reinterpret_cast performs selected low-level conversions, primarily involving pointers and references. The cast itself does not authorize access through an incompatible type: aliasing, alignment, and object-lifetime rules still apply.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

reinterpret_cast<T>(expression)

reinterpret_cast<T>(expression) performs selected low-level conversions, not ordinary value conversion. A reference cast creates no copy and calls no constructor. The operator cannot remove const.

Typical uses include conversions between object pointer types and conversions from pointers to sufficiently large integer types. The pointer-to-integer mapping is implementation-defined. Valid syntax does not guarantee that using the result is safe.

Accessing an object through a disallowed type causes undefined behavior. The types char, unsigned char, and std::byte can access an object's representation; this does not permit treating an int object as a float. Alignment and lifetime requirements still apply.

The example converts a pointer to unsigned char*, restores int*, and reads the original object. It does not read individual bytes, so its output does not depend on byte order. When you need a separate value with another type's bit representation, consider std::bit_cast: it requires equal sizes and trivially copyable types, and the resulting representation must be valid for the destination type.

Examples

#include <iostream>

int main() {
    int value = 42;
    unsigned char* bytes = reinterpret_cast<unsigned char*>(&value);
    int* restored = reinterpret_cast<int*>(bytes);
    std::cout << std::boolalpha << (restored == &value)
              << ' ' << *restored << '\n';
}

Result

true 42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources