Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          casts/casts4.cc - Examples of reinterpret_cast.Lecture 3 - slide 6 : 27
Program 6

// Illustration of reinterpret cast.

#include <iostream>
#include <cassert>
#include <cstdint>  // because of uintptr_t

int main(){
  using namespace std;

  // Casting between pointer and unsinged integers.
  int i;
  uintptr_t i_adr = reinterpret_cast<uintptr_t>(&i);     // Casting the address of i to an an unsigned int
  cout << i_adr << endl << endl;
  int *j = reinterpret_cast<int*>(i_adr);                // Casting the integer back to a pointer.
  assert(j == &i);                                       // The roundtrip must succeed.


  // Attempting reinterpret cast from double to long long int:
  static_assert(sizeof(long long int) == 
                sizeof(double), 
                "unexpected sizes");                     // Asserts statically that both types are of same byte length

  double e{124.567};
  long long int m
    {reinterpret_cast<long long int>(e)};                // Error: Attempting to reinterpret a double as a long long int

  // Doing the trick via pointers:
  double *pe{&e};                          
  long long int *llip
   {reinterpret_cast<long long int*>(pe)};                // OK
  std::cout << *llip << std::endl;                        // 4638466040292848959
}