I understand that reinterpret_cast is dangerous, I’m just doing this to test it. I have the following code:
int x = 0;
double y = reinterpret_cast<double>(x);
When I try to compile the program, it gives me an error saying
invalid cast from type ‘float’ to type ‘double
What’s going on? I thought reinterpret_cast was the rogue cast that you could use to convert apples to submarines, why won’t this simple cast compile?
Perhaps a better way of thinking of
reinterpret_castis the rouge operator that can "convert" pointers to apples as pointers to submarines.By assigning y to the value returned by the cast you’re not really casting the value
x, you’re converting it. That is,ydoesn’t point toxand pretend that it points to a float. Conversion constructs a new value of typefloatand assigns it the value fromx. There are several ways to do this conversion in C++, among them:The only real difference being the last one (an implicit conversion) will generate a compiler diagnostic on higher warning levels. But they all do functionally the same thing — and in many case actually the same thing, as in the same machine code.
Now if you really do want to pretend that
xis a float, then you really do want to castx, by doing this:You can see how dangerous this is. In fact, the output when I run this on my machine is
1, which is decidedly not 42+1.