Skip to content
Quantoros

Why prefer staticcast, dynamiccast, constcast, and reinterpretcast over C-style casts?

C++Level: IntermediateCasting & Type Conversions

Why prefer static_cast, dynamic_cast, const_cast, and reinterpret_cast over C-style casts?

Hints
  • Identify types, object lifetimes and compile-time decisions.
  • Separate language guarantees from a particular compiler's behavior.

Answer

C-Style Cast (Legacy Casting)

:Source: src/casting/c-style

C-style casts use the syntax (type)expression inherited from C. While concise, they are dangerous because the compiler tries const_cast, static_cast, and reinterpret_cast in sequence until one succeeds. This makes it hard to know which conversion actually happens. The lack of visual distinction also makes C-style casts difficult to search for in large codebases. Modern C++ code should prefer explicit C++ casts for clarity, safety, and maintainability.

#include <cmath>
#include <iostream>

int main(int argc, char *argv[]) {
  double x = M_PI;
  int xx = (int)x;  // Truncates: 3.14159... -> 3
  std::cout << xx << "\n";

  long z = LONG_MAX;
  int zz = (int)z;  // Dangerous: overflow, undefined behavior
  std::cout << zz << "\n";
}

warning:

C-style casts bypass type safety checks and can silently perform dangerous conversions. Prefer static_cast for safe conversions and avoid C-style casts in modern C++ code.

Answer section

Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT

Related questions