C++ Type Casting
Type casting is the change of a value from one type to another type. The static_cast tool writes the new type for the changed value.
A decimal becomes whole
static_cast<int> changes 9.99 to an int. The decimal part drops away, so the print shows 9.
#include <iostream>
int main() {
std::cout << static_cast<int>(9.99) << "\n";
return 0;
}Two divisions
The cast makes 7 a double, so the first division keeps its decimal part. The second division uses whole numbers and drops the part.
#include <iostream>
int main() {
std::cout << static_cast<double>(7) / 2 << "\n";
std::cout << 7 / 2 << "\n";
return 0;
}A character code
Each character has a number code. A cast to int shows the code for the letter A.
#include <iostream>
int main() {
std::cout << static_cast<int>('A') << "\n";
return 0;
}Text cannot become a number
This program tries to store text in an int variable. The compiler refuses the program and prints the error line below.
#include <iostream>
int main() {
int count = "many";
std::cout << count << "\n";
return 0;
}Example
#include <iostream>
int main() {
int celsius = 25;
double fahrenheit = static_cast<double>(celsius) * 9 / 5 + 32;
std::cout << "Celsius: " << celsius << "\n";
std::cout << "Fahrenheit: " << fahrenheit << "\n";
return 0;
}Key points
- Use static_cast to change a value to a new type.
- A cast to int drops the decimal part of a value.
- A cast to double lets a division keep its decimal part.
- Each character has a number code.
- A cast of a char to int shows the number code of the character.
- A cast cannot turn text into a number.
In this example, celsius holds the int value 25. The cast makes a double copy of that value for the formula. The formula gives 77, and the two lines print the Celsius and Fahrenheit values.
Note
A cast makes a changed copy. The original value keeps its own type.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C++ Compiler
Exercise
What does static_cast<int>(9.99) print?