Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can static_cast can cast an int to char but not reinterpret_cast?

I'm not sure if it has been asked earlier, but must have been I believe. Consider the simple line for start of question :

int a ;
char b = reinterpret_cast<char> (a);

I understand reinterpret_cast interpret the bits pattern of type x as type y, ofcouse it shouldn't work due to size mismatch and indeed it doesn't.

Now consider this another code:

int a ;
char b = static_cast<char> (a);

This works! . Now my question is how it can work ? I mean does the compiler chops off the bits? . I am certain sizeof(char) < sizeof(int) . If that, reinterpret_cast should also work by same technique ?

like image 427
M3taSpl0it Avatar asked Feb 17 '13 17:02

M3taSpl0it


People also ask

Can you cast an int to a char C++?

The integer can be converted to a character using the static_cast function. Below is the C++ program to convert int to char using static_cast: C++

How does static_cast int work?

The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.

What static_cast is actually doing?

static_cast can be used to convert between pointers to related classes (up or down the inheritance hierarchy). It can also perform implicit conversions.

Can static_cast throw exception?

static_cast can't throw exception since static_cast is not runtime cast, if some cannot be casted, code will not compiles. But if it compiles and cast is bad - result is undefined.


1 Answers

There is a well-defined conversion from int to char; that's what static_cast does. In fact, you don't need the cast; you can just use an assignment here. On the other hand, reinterpret_cast says to pretend that the bits in an object of one type represent an object of another type; for some types that's okay (more or less), but there's no sensible way to pretend that the bits in an int can be used as the bits in a char without applying a conversion, and reinterpret_cast doesn't do that.

like image 195
Pete Becker Avatar answered Oct 25 '22 00:10

Pete Becker