Tag Archives: c++ casting

Static Casting in C++

There are four types of casting in C++:

  • Static casting
  • Dynamic casting
  • Const casting
  • Reinterpreted casting

Each of the casting exists for a purpose, and should be used with carefulness. This article will talk broadly about what each of the casting does, their use case, and what programmers should know when using them. Since each type of casting is a huge topic, there are countless things to know about them, this article only talks about a tip of the iceberg. In the later articles, I will talk about each of them more spcifically.

Static casting

Static casting is unary operator in C++ that allows one type of variable to be statically converted into another type in compile time with a strict type check (I will talk about this later). This is either done exmplicitly using static_cast<type> or implicitly. Among all other casting, this should be the first cast you should attempt to use when performing an object type casting since it is done statically, thus, won’t affect the program performance.

int i = 100;
float j = static_cast<float>(i);
char p = (char)i;
double k = i;
cout << "float: " << j << endl << "double: " << k << endl << "char: " << p;

Output:

float: 100
double: 100
char: d

Above code example shows three ways of using static casting. Line 3 used static cast to cast an int to a float, this is the most common way to write static casting, and optimally, it should be the only way to write it most of the time because the following two ways are tricky.

Line 4 uses c-style casting, which could implicitly decide which casting style should used in compile time. In this case, it uses static cast. But sometimes static casting might not work, a strong casting like reinterpret casting is then used. This casting should be avoid if the programmer wants to be sure about what casting style is being used.

Line 5 is an implicit casting or conversion, where the compiler does the casting in order to fullfill a desired operation. The casting is always an upgrade, which means float will always be casted to a double (32 bit -> 64 bit), int will always be casted into a long (same concept). However, it may seems convenient, there could be potential data loses (such as casting a signed to an unsigned).

Unfinished.