Table of Contents
Type casting converts a value from one data type to another explicitly. Unlike implicit type conversion, the conversion is requested by the programmer using a cast expression.
This example demonstrates the use of static_cast to convert an integer value to a floating-point value.
Source Code #
#include <iostream>
int main()
{
int total_marks = 425;
float average = static_cast<float>(total_marks) / 5;
std::cout << "Average Marks: " << average << '\n';
return 0;
}
Output #
Average Marks: 85
Explanation #
int total_marks = 425;declares an integer variable containing the total marks.static_cast<float>(total_marks)explicitly converts the integer value to thefloattype.- The conversion is performed before the division operation. As a result, floating-point division is used, producing a floating-point result.
static_castis the preferred C++ cast for well-defined conversions between compatible data types because it is explicit and easier to identify than C-style casts.- Without the cast, the expression
total_marks / 5performs integer division because both operands are integers. std::cout << "Average Marks: " << average << '\n';prints the floating-point result.return 0;terminates the program successfully.