The Big Master

Automatic Type conversion

In C++, automatic conversion, also known as implicit type conversion or automatic...

In C++, automatic conversion, also known as implicit type conversion or automatic type promotion, refers to the process by which the compiler automatically converts one type of data to another type in certain situations. It occurs when the conversion is safe and consistent, and no explicit type casting is required.

When two operands of different types are encountered in the same expression, the lower-type variable is converted to the type of the higher-type variable.

#include <iostream>

int main() {
    int intValue = 10;
    double doubleValue = intValue; // Implicit conversion from int to double

    std::cout << "intValue: " << intValue << std::endl;
    std::cout << "doubleValue: " << doubleValue << std::endl;

    return 0;
}
#include <iostream>
using namespace std;
int main()
{
    int x = 10;      // Declare an integer variable x and initialize it with the value 10.
    float y = x;     // Perform type conversion: assign the value of x to the float variable y.
    cout << y;       // Output the value of y (which is now 10.0 due to type conversion) to the console.
    return 0;        // Return 0 to indicate successful program execution.
}
#include <iostream>
using namespace std;

int main()
{
    int x = 10;      // Declare an integer variable x and initialize it with the value 10.
    float y = 20;    // Declare a float variable y and initialize it with the value 20.
    double z;        // Declare a double variable z.

    z = x + y;       // Perform type promotion: The integer value x is promoted to a float before being added to y, and the result is stored in z.
    
    cout << z;       // Output the value of z to the console.
    
    return 0;
}
#include <iostream>
using namespace std;
int main()
{	// type conversion, auto conversion
    float x = 10.1 ;
    int  z = x   ;     // value after decimal will be trancated. 10 will be stored in z 
    cout << z << endl ; 
    return 0;
}