×
>
<

Aptitude

Type conversion in C++

What is implicit data type conversion in C++?

Type conversion is a process in which a variable of one data type is converted to another data type. For example, if we are adding two number one of int type and another of short int type then we need to typecast short int variable to int making them both int type so that we can add them.

Type conversion is done in two ways in C++ one is explicit type conversion and the second is implicit type conversion. In simple words, explicit type conversion is done by the user hence known as user-defined type conversion, and implicit type conversion is done by compiler itself hence known as automatic type conversion. In this article, we will learn more about implicit type conversion in C++

Implicit data type conversion in C++

Example of Type Conversion –

Implicit type conversion is a process that is done by the compiler itself without any human effort i.e. no external human trigger is required for the process of converting a variable of one data type to another. It is also known as automatic type conversion. If an expression contains variables of different data types so to avoid data loss the variable of smaller data type(low priority data type) is converted to the bigger data type (high priority data type).

Example
  
int a=5;
short b=2;
int c= a+b;
  

Here in integer type variable ‘c’ addition of ‘a’, an integer type variable and ‘b’, a short type variable is stored. So the compiler will implicitly convert the low priority data type i.e. short to higher priority data type i.e. integer.

C++ Order of Data Types
C++ program to show implicit data type conversion
Example :
  
#include 
using namespace std;
int main()
{
 int i = 10; 
 char c = 'a'; 
 float f=1.1;
 f = f + i ;
 //i get converted to float type from integer type.

 i = i + c;
 //c get converted to int type from char type i.e. to equivalent ASCII value of 'a' i.e. 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:

As we have read in the article that implicit type conversion does not require any human efforts and is done by compiler itself but this process can sometimes lead to data loss when, signed is implicitly converted to unsigned and also lead to overflow when, long long is implicitly converted to float.