C++ › Casting & Conversions

What is static_cast used for?

Beginner

Answer

static_cast performs well-defined conversions known at compile time: numeric conversions (int to double), converting between related pointer types in a hierarchy (up or down without runtime check), void* to typed pointer, and explicit calls to conversion operators/constructors. It does no runtime checking, so an invalid downcast is undefined behavior.
int i = 7;
double d = static_cast<double>(i) / 2;  // 3.5
Real-world example static_cast converts an enum to its underlying int for arithmetic or indexing.

Common follow-ups: Does static_cast check at runtime? | When is a static_cast downcast unsafe?