Polyglot CheatSheet - Type Casting and Type Conversion

Updated: 2021-11-19

Type Casting vs Type Conversion

  • type conversion: implicit, made automatically by compiler (a.k.a. coercion)
  • type casting: explicit, done by the programmerm using a cast operator

Type Casting

C++

  • static_cast performs no runtime checks. use it in cases like converting float to int, char to int, etc. Also used in CRTP
  • dynamic_cast: used for handling polymorphism. Only used used in inheritence when casting from base class to derived class.
  • C-style cast: A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast. More powerful as it combines all of const_cast, static_cast and reinterpret_cast, but it's also unsafe
  • const_cast: can be used to remove or add const to a variable.
  • reinterpret_cast: used for reinterpreting bit patterns and is extremely low level, primarily for things like turning a raw data bit stream into actual data or storing data in the low bits of an aligned pointer.

Rust

Explicit type conversion (casting) can be performed using the as keyword.

let integer = decimal as u8;

Saturating cast: when casting from float to int. If the floating point value exceeds the upper bound or is less than the lower bound, the returned value will be equal to the bound crossed.

// result is 255
300.0_f32 as u8

// result is 0
-100.0_f32 as u8

// result is 0
f32::NAN as u8

Use unsafe to bypass this, but may overflow:

unsafe {
    // result is 44
    300.0_f32.to_int_unchecked::<u8>()

    // result is 156
    (-100.0_f32).to_int_unchecked::<u8>()
}

Type Conversion

Rust

Rust provides no implicit type conversion (coercion) between primitive types.