Loading lessons...
Type Conversion and static_cast
Type Conversion and static_cast
Values often need to move between types - an int into a double, a double into an int. That movement is called type conversion.
Implicit conversion
Sometimes C++ converts types for you, automatically. This is implicit conversion:
int a = 5;
double b = a; // 5 -> 5.0, no complaint
cout << b; // 5
Losing no information (like int to double) is safe and silent. But the reverse can be dangerous:
double pi = 3.99;
int x = pi; // x becomes 3, the .99 silently disappears
This is narrowing: data is quietly lost. C++ lets it happen with the old = style, which is why brace initialization refuses it.
The integer division trap
Here's a classic bug. Dividing two ints does integer division - the fractional part is thrown away:
int a = 7;
int b = 2;
cout << a / b; // 3, not 3.5!
7 / 2 is 3 because both operands are integers. If at least one operand is a double, you get real division.
Explicit conversion: static_cast
To convert on purpose, use a cast. The modern C++ cast is static_cast:
int a = 7;
int b = 2;
double result = static_cast<double>(a) / b; // 3.5
static_cast<double>(a) converts a to a double just for that expression, so the division now sees a double and gives 3.5.
double pi = 3.99;
int x = static_cast<int>(pi); // 3 - you asked for it explicitly
The old C-style cast
You may see the older (int)value style in old code. It still works, but static_cast<int>(value) is preferred: it's more visible, more precise, and safer.
TL;DR
- Implicit conversion happens automatically (int to double is safe).
- Narrowing quietly loses data (double to int drops the fraction).
- Integer division:
7 / 2is3, not3.5. - Use
static_cast<newType>(value)for explicit, readable conversion. - Fix division by casting one operand:
static_cast<double>(a) / b.