×
>
<

C++ Programming

C++ Type Conversion | CrackEase

Type conversion in C++

What is implicit data type conversion in C++?

Type conversion is the process of converting a variable from one data type to another. For example, when adding two numbers where one is int and the other is short, the compiler may convert the short to int so the operation happens in a single type.

Conversion in C++ can be explicit (performed by the programmer with a cast) or implicit (performed automatically by the compiler). Explicit conversion is also called user-defined or cast conversion; implicit conversion is automatic and performed by the compiler. Below we focus on implicit (automatic) conversions.

Implicit data type conversion in C++

Example of Type Conversion –

Implicit type conversion (automatic conversion) is performed by the compiler when an expression contains different data types. To avoid loss of information, the compiler converts the lower-priority (smaller) type to the higher-priority (larger) type.

Example
  
int a = 5;
short b = 2;
int c = a + b; // 'b' is implicitly converted to int
  

Here the short value b is converted to int so the addition is performed as int and stored in c.

C++ Order of Data Types
C++ data type priority order
C++ program to show implicit data type conversion
Example :
  
#include <iostream>
using namespace std;
int main()
{
    int i = 10; 
    char c = 'a'; 
    float f = 1.1f;
    f = f + i; 
    // 'i' is promoted to float for this operation

    i = i + c;
    // 'c' is promoted to int using its ASCII code ('a' -> 97)

    cout << "Value of i = " << i << endl;
    cout << "Value of c = " << c << endl;
    cout << "Value of f = " << f << endl;
    return 0;
}
  

Output :

  
Value of i = 107
Value of c = a
Value of f = 11.1
  
Conclusion:

Implicit conversions are convenient but can cause surprises: they may cause precision loss (e.g., converting a large integer to float), change signedness, or produce unexpected promotions. Be mindful of type priorities and use explicit casts when you want to control conversion behavior.

Footer Content | CrackEase