C++ static_cast Keyword
Example
Convert a double to an int:
double myDouble = 9.99;
int myInt = static_cast<int>(myDouble);
cout << myInt;
Definition and Usage
The static_cast keyword converts a value from one type to another. Write the new type inside < >, and the value inside the parentheses.
When you convert a double to an int, the decimals are cut off, not rounded. That is why 9.99 becomes 9, not 10.
static_cast is the recommended way to convert values in C++. The older C-style way, (int) myDouble, does the same thing, but static_cast is easier to spot and safer to use.
Related Pages
Read more about type conversion in our C++ Type Conversion Tutorial.