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'
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:
So to break this line of code into more details
*reinterpret_cast<int*>(&a);
:a
reinterpret_cast
to anint*
int*
that points toa
int
Now when I run this I get
1094713344
, the reason for that is 12 as afloat
using IEEE is represented as0100 0001 0100 0000 0000 0000 0000 0000
in binary. Now take that binary and read it asint
, then you end up with1094713344
.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.