c++ – What is static_cast for, how does it work and where is it used?

Question:

What is static_cast for, how does it work and where is it used?

Answer:

static_cast has a lot of different uses. Its idea is this: it's a limited C-style cast. The restriction is needed because a C-style cast can cast anything to anything (well, almost), and thus can hide the error. For example, you can accidentally cast const char* to char* , causing a crash on some systems with hardware support for const memory. static_cast won't let you do that.

Most of the time, when you want to do an explicit type conversion (and I hope this is rare enough), you want static_cast .

The formal list of everything that static_cast can do is very long , I will list only the most important things that it can (and also that it can't ):

What is possible:

  1. Converting a pointer to a parent class to a pointer to a child class. The object pointed to must be a valid child class, otherwise undefined behavior. If you're unsure and want to check if an object has the right subclass, use dynamic_cast (it's designed specifically for that).
  2. Conversions between numeric types. int , long , char , unsigned int – all of them can be cast into each other using static_cast .
  3. You can cast any expression to void . The result will be evaluated and discarded (but the side effects will, of course, be executed).
  4. static_cast can cast the nullptr constant to any pointer type. This is usually not necessary and you can rely on implicit type conversion, but sometimes (for example, to select the desired function overload), this can be useful.

What is not allowed:

  1. Conversion between pointers to basically incompatible types. For example, a pointer to double cannot be cast to a pointer to int . For type safety tricks, use reinterpret_cast .
  2. Pointers to types, as well as types themselves with incompatible const and/or volatile attributes. If you need to break const-correctness, use const_cast .
  3. Of course, you can't cast a member function pointer to a regular function pointer, or a code pointer to a data pointer. For such dirty hacks, use reinterpret_cast .

Another reason to use static_cast (as well as other C++-specific type conversions) is that it can be easily found in sources, both by eyes and by search tools. Cish casting (especially its functional variety) is very easy to miss in the code.


For comparison, the "usual" type conversion (C-style cast) is equivalent to the following sequence:

  1. const_cast .
  2. If const_cast cannot produce the desired result, then static_cast (but with a cast to an underdeclared type allowed)
  3. If it still doesn't work, then the compiler tries to add static_cast to the tail of const_cast .
  4. If this fails, then reinterpret_cast .
  5. … and if it fails, then const_cast appended to it.
Scroll to Top