| casts/casts4-compilable.cc - The compilable parts of the program from above. | Lecture 3 - slide 6 : 27 Program 7 |
// The compilable parts of the program from above.
#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.
// Doing the trick (double to long long int) via pointers:
static_assert(sizeof(long long int) ==
sizeof(double),
"unexpected sizes"); // Asserts statically that both types are of same byte length
double e{124.567};
double *pe{&e};
long long int *llip
{reinterpret_cast<long long int*>(pe)}; // OK (or at least done).
std::cout << *llip << std::endl; // 4638466040292848959
}