M3taSpl0it
M3taSpl0it

Reputation: 3027

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 ?

Upvotes: 10

Views: 22858

Answers (2)

Ron Natalie
Ron Natalie

Reputation: 51

static_cast can either force a defined conversion to happen or it can reverse a defined conversion (other than for adding or removing const/volatile). You think that reinterpret_cast is some super cast that can do anything. That is not the case. It has a set of defined conversions.

It can convert pointers of one type to a pointer of another (as long as const/volatile is preserved). It can similarly do so for references. It can cast pointers to integral types and vice versa.

Other than that, it does NOT do anything and your program is not well-formed.

Upvotes: 5

Pete Becker
Pete Becker

Reputation: 76498

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.

Upvotes: 9

Related Questions