C++ – How to Use reinterpret_cast in C++

c++

I know the reinterpret_cast in C++ can be used in this way:

float a = 0;
int b = *reinterpret_cast<int*>(&a);

But why cannot cast it directly?

float a = 0;
int b = reinterpret_cast<int>(a);

error: invalid cast from type 'float' to type 'int'

Best Answer

All reinterpret_cast does is allow you to read the memory you passed in a different way. You give it a memory location and you ask it to read that memory as if it was what you asked it to. This is why it can only be used with pointers and references.

Let's take this code as an example:

#include <iostream>

int main()
{
    float a = 12;
    int b = *reinterpret_cast<int*>(&a);

    std::cout << b;
}

So to break this line of code into more details *reinterpret_cast<int*>(&a);:

  1. Take the address of a
  2. reinterpret_cast to an int*
  3. Get back an int* that points to a
  4. Dereference the value of the returned pointer as int

Now when I run this I get 1094713344, the reason for that is 12 as a float using IEEE is represented as 0100 0001 0100 0000 0000 0000 0000 0000 in binary. Now take that binary and read it as int, then you end up with 1094713344.

This is why reinterpret_cast is considered to be very dangerous and why it should NOT be used in this type of cases.

You should only use it when you have a pointer pointing to memory and you need to read that memory in a certain way and you know that the memory can be read in that way.

Related Question