In programming languages, type casting (or type conversions) allows us to change a variable from one data type to another.1 For example, converting an integer to a float. The purpose of casting differs depending on the language’s type system.

  • In dynamically typed languages, type casting is done at runtime. Variables don’t hold a fixed type, but the values they hold do have types. Casting is usually implicit and done to make an operation valid, i.e., 5 + "2" == "52" in JavaScript.
  • In statically typed languages, type casting is usually evaluated at compile-time. They’re usually done explicitly by the developer and are used to ensure type safety given certain operations.

Language-specific

In C/C++

Certain types are implicitly converted automatically by the compiler. For example, numeric types can be implicitly coerced such that they can compose expressions with each other:

float d;
long long l; // int64_t
int i; // int32_t
// all valid!
if (d > i) d = i;
if (i > l) l = i;
if (d == l) d *= 2;

This allows different types to be able to operate on each other. But implicit conversion can lead to behaviour we don’t intend: for example, implicit conversion from float to int will truncate the fractional part. For other types, data may also be lost.

The traditional explicit conversion schemes in C/C++ involve having the type in parentheses:

int32_t x = (int)((float)5 + 1.9); // == 6

This is not ideal: it can broadly refer to any of const_cast, static_cast, or reinterpret_cast. It is ambiguous and doesn’t allow users to specify their intent.

Modern casting

Modern C++ codebases should instead use static_cast, reinterpret_cast, const_cast, or dynamic_cast. All follow the syntax: _cast<target_typ>(expr).

static_cast is a compile-time conversion. It is the strictest possible conversion.

Footnotes

  1. Prof Stumm says it’s usually a pretty bad practice to type cast. He said, “you’ll have to write a three page report justifying why.” This is a strange statement to make, and modern static_cast are used widely in production codebases. Maybe he means traditional explicit conversions?