Static_cast – cpp

Static casting (static_cast) is when you want to change the type of the variable e.g. if you want to have a the number of pies that are left to be 0.5 instead of a whole value then you would need to change the integer value to a double. The static_cast can change one type to another, as long as it is compatible.

The general syntax for static_cast is

returnvalue = static_cast<returntype>(value to cast)

Where the return value is the value returned from the casting, returntype is the variable type that you want to have (e.g. double) and the value to cast speaks for itself.

For the example above about pies, the code would be

     int pie = 3;
     double fl = static_cast<double>(pie);

The static_cast(ing) and also other types of casting are the long form as such compared to the standard C version of

   double fl = (double)pie;

But with the static_cast you can be sure that the implementation will be type checked and also because of the classes etc then you need to type check the results unless you may have some value that is not want you was wanting.

Leave a Reply

Your email address will not be published. Required fields are marked *