C++ static_cast Explicit Conversions

Introduction

We can explicitly convert the value of one type to another.

Let us start with the static_ cast function.

This function converts between implicitly convertible types.

A signature of the function is:

static_cast<type_to_convert_to>(value_to_convert_from) 

If we want to convert from a double to int we write:

int main() 
{ 
    auto myinteger = static_cast<int>(123.456); 
} 

Prefer this verbose function to implicit conversions, as the static_cast is the idiomatic way of converting between convertible types.

This function performs a compile-time conversion.




PreviousNext

Related