Type conversion
- C++ course
- Beginner
- Lesson 11/116
- 4 min
Learn static_cast and implicit type conversion.
Type conversion
Sometimes you need to convert a value from one type to another: double to int, int to char and so on. In C++ you use static_cast for this.
The syntax is static_cast<target_type>(value). For example, static_cast<int>(9.99) gives 9; the decimal part is truncated (not rounded).
C-style casts ((int)x) work in C++ but are not recommended. static_cast is safer: it checks type compatibility at compile time and clearly shows intent.
Narrowing conversion
Converting from a larger type to a smaller type is called a narrowing conversion: for example, double to int. Data may be lost; 9.99 becomes 9 and .99 is gone.
static_cast shows you accept this loss consciously. Brace initialization int x{9.99}; prevents narrowing and gives a compile error.
The reverse direction (small to large, e.g. int to double) is safe; no data is lost. Still, writing static_cast explicitly shows intent.
Practice Convert a decimal to an integer
Inside main, the declaration double price = 9.99; is already there. Use static_cast<int> to convert price to int and assign it to a variable named whole. Then print whole with std::cout using std::endl.
Starter code
#include <iostream>
int main() {
double price = 9.99;
// Convert price to int with static_cast and assign to whole
// Print whole with std::cout
return 0;
}Sample solution
#include <iostream>
int main() {
double price = 9.99;
// Convert price to int with static_cast and assign to whole
int whole = static_cast<int>(price);
// Print whole with std::cout
std::cout << whole << std::endl;
return 0;
}Expected output
9
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match conversions
| Term | Meaning |
|---|---|
static_cast<int>(9.99) |
9 |
static_cast<double>(5) |
5.0 |
static_cast<char>(65) |
'A' |
static_cast<int>(true) |
1 |
2 static_cast syntax
int whole = static_cast<____>(9.99);
int whole = static_cast<int>(9.99);
Explanation: static_cast<int>(9.99) gives 9.
3 What is the result of static_cast<int>(9.99)?
- 10 (rounded)
- 9 (truncated) Correct answer
- 9.99 (unchanged)
- Compile error
Explanation: static_cast<int> truncates the decimal; 9.99 becomes 9.