liveBook · Manning

Static_cast

As explained in 100 C++ Mistakes and How to Avoid Them

static_cast is a C++ cast expression that performs compile-time checked conversions between related or otherwise compatible types.

static_cast performs a compile-time checked conversion between compatible data types. It is the C++-style choice for ordinary conversions, such as truncating a double to an integer, while rejecting incompatible conversions. section 5.6

Replacing an unsafe C-style cast

A C-style cast can hide what conversion is intended. In the cleaned-up example, static_cast<double>(n) makes the numeric conversion explicit, while static_cast<double*>(msg) is rejected because the pointer types are incompatible. Use static_cast only when the conversion is as safe as you understand it to be. section 5.6

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines compiler compatibility checking and demonstrates numeric conversion, but defers deeper conversion mechanics.
Examples
Demonstrates converting an integer to double and rejecting a double-pointer conversion from a character array.
What you can do after
Evaluate/understand when an explicit compatible conversion is appropriate and when the compiler should reject it.
How it connects
Contrasts static_cast with const_cast, reinterpret_cast, dynamic_cast, and C-style casts.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.