<<< C++ way of conversions between types | Index | Safer casting with dynamic_cast >>> |
Use static_cast in place of most C-style casts.
Use static_cast when converting from one type to another, and the types are related:
Converting to and from void*
Converting float to int
Converting enum to int
Other similar conversions when types are related (ptr to ptr).
// Trust the programmer, with compiler help: double d = 3.5; int x = static_cast< int >( d ); // NO ROUNDING: x gets 3, not 4! int* p = static_cast< int* >( malloc( sizeof( int ) * 100 ) );
Compiler will help the conversion (it may do some checking.)
Warning: using static_cast often is not portable, because types could have different sizes on different systems.
<<< C++ way of conversions between types | Index | Safer casting with dynamic_cast >>> |