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 ?
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++
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.
static_cast can be used to convert between pointers to related classes (up or down the inheritance hierarchy). It can also perform implicit conversions.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With