How can static_cast use int for char, but not for reinterpret_cast?

I'm not sure if this has been asked before, but I must suppose. Consider a simple line to start the question:

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

I understand that reinterpret_cast interprets the bit pattern of type x as type y, ofcouse it should not work due to size mismatch, and in fact it is not.

Now consider the following code:

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

It works !, Now my question is, how can it work? I mean, does the compiler beat the bits ?, I'm sure sizeof(char) < sizeof(int) . If so, should reinterpret_cast work the same way?

+6
source share
2 answers

There is a clear conversion from int to char ; what does static_cast . You really don't need a throw; you can just use the assignment here. reinterpret_cast , on the other hand, says it pretends that bits in an object of one type represent an object of another type; for some types that are suitable (more or less), but there is no reasonable way to pretend that bits in int can be used as bits in char without conversion, and reinterpret_cast does not.

+6
source

static_cast can either force a specific conversion, or it can change a specific conversion (except for adding or removing the / volatile constant). You think reinterpret_cast is a super-cast that can do something. This is not relevant. It has a set of specific transformations.

It can convert pointers of one type to a pointer of another (as long as const / volatile persists). Similarly, this can be done for links. It can point to pointers to integral types and vice versa.

Other than that, it does nothing, and your program is not correct.

+3
source

All Articles