Why do we have reinterpret_cast in C++ when two chained static_cast can do its job?

There are things that reinterpret_cast can do that no sequence of static_casts can do (all from C++03 5.2.10): A pointer can be explicitly converted to any integral type large enough to hold it. A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer to a function can be … Read more

Should I use static_cast or reinterpret_cast when casting a void* to whatever

Use static_cast: it is the narrowest cast that exactly describes what conversion is made here. There’s a misconception that using reinterpret_cast would be a better match because it means “completely ignore type safety and just cast from A to B”. However, this doesn’t actually describe the effect of a reinterpret_cast. Rather, reinterpret_cast has a number of … Read more

Why use static_cast(x) instead of (int)x?

The main reason is that classic C casts make no distinction between what we call static_cast<>(), reinterpret_cast<>(), const_cast<>(), and dynamic_cast<>(). These four things are completely different. A static_cast<>() is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it’s a bit risky is … Read more

tech