• Home
  • 1.14 Type Conversion

1.14 Type Conversion

View Categories

1.14 Type Conversion

< 1 min read

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 value 85.
  • float average = marks; assigns an int value to a float variable. 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.
  • average stores the value as 85.0, although the default formatting of std::cout omits the trailing decimal part.
  • std::cout prints both variables using the formatting appropriate for their respective data types.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *