Table of Contents
Type conversion changes a value from one data type to another. C++ performs conversions automatically when compatible data types are used together in an expression. This process is known as implicit type conversion.
This example demonstrates how an integer value is automatically converted to a floating-point value during assignment.
Source Code #
#include <iostream>
int main()
{
int marks = 85;
float average = marks;
std::cout << "Marks: " << marks << '\n';
std::cout << "Average: " << average << '\n';
return 0;
}
Output #
Marks: 85
Average: 85
Explanation #
int marks = 85;declares an integer variable and initializes it with the value85.float average = marks;assigns anintvalue to afloatvariable. The compiler automatically converts the integer value to a floating-point value.- This automatic conversion is called implicit type conversion because it is performed without requiring an explicit cast.
- Implicit conversions are performed only when the compiler determines that the conversion is valid.
averagestores the value as85.0, although the default formatting ofstd::coutomits the trailing decimal part.std::coutprints both variables using the formatting appropriate for their respective data types.return 0;terminates the program successfully.