Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use reinterpret_cast in C++?

Tags:

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'
like image 919
sunlight07 Avatar asked Aug 31 '13 05:08

sunlight07


People also ask

What is Reinterpret_cast in C?

The reinterpret_cast operator converts a null pointer value to the null pointer value of the destination type.

Should you use Reinterpret_cast?

Purpose for using reinterpret_cast It is used when we want to work with bits. If we use this type of cast then it becomes a non-portable product. So, it is suggested not to use this concept unless required. It is only used to typecast any pointer to its original type.

What is C style cast?

C-style casts can be used to convert any type into any other type, potentially with unsafe results (such as casting an integer into a pointer type). (<type>)<value> This example casts an int to a double for the purpose of avoiding truncation due to integer division: double result = (double)4/5; Popular pages.


2 Answers

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. Deference 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 unsigned 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.

like image 63
Caesar Avatar answered Oct 01 '22 19:10

Caesar


You can't reinterpret_cast in the case you give because reinterpret_cast takes only either a int to convert to a pointer, or the reverse, and follows additional similar rules.

There is a summary of these rules there: http://en.cppreference.com/w/cpp/language/reinterpret_cast

like image 27
Klaim Avatar answered Oct 01 '22 19:10

Klaim