Implicit type conversion in C++ | Automatic type conversion in C++

Implicit type conversion in c++

Implicit type conversion in C++ | Automatic type conversion in C++

Implicit conversion in C++ is also called automatic type conversion in C++. It is the process in which output of arithmetic expression automatically gets converted into a specific data type.

Basic rule of Automatic type conversion is, output of arithmetic expression will be of that data type that has the highest number of bytes and range.

Example:

In an arithmetic expression if one value is of short type and other is of int type, the output is of int type because int type value more size and better range of values as compared to short data type.

Rules of implicit conversion

Data type of first value Data type of Second Value Data type of Result
short short short
short int int
short long long
short float float
short double double
short long double long double
short char short
int int int
int long long
int float float
int double double
int long double long double
int char int
long long long
long float float
long double double
long long double long double
long char long
float float float
float double double
float long double long double
float char float
double double double
double long double long double
double char double
long double long double long double
long double char long double
char char char

 //Program to demonstrate Implicit conversion

#include<iostream> 
using namespace std;
int main()
{
  int n;
  double m;
  n=10/3;    //Line 7
  cout<<"\n10/3="<<n;  
  m=10/3;         //Line 9
  cout<<"\n10/3="<<m; 
  n=10.0/3;         //Line 11
  cout<<"\n10.0/3="<<n;  
  m=10.0/3;         //Line 13
  cout<<"\n10.0/3="<<n; 
  return 0;
}

Output:

10/3=3
10/3=3.000000
10.0/3=3
10.0/3=3.333333

** In line 7 of above program, 10 and 3 are int type values so result of 10/3 is of int type i.e. 3 which is assigned to variable which is of int type. So n  contains 3.

In line 9, 10 and 3 are int type values so result of 10/3 is of int type i.e. 3 which is assigned to variable which is of double type. So m  contains 3.000000.

In line 11, 10.0 is double type value  and 3 is an  int type value so result of 10.0/3 is of double type i.e. 3.333333 which is assigned to variable which is of int type. So n  contains 3.

In line 13, 10.0 is double type value  and 3 is an  int type value so result of 10.0/3 is of double type i.e. 3.333333 which is assigned to variable which is of double type. So m  contains 3.333333.



Spread the love
Lesson tags: Automatic type conversion in C++, implicit conversion in c
Back to: C++ Programming Notes
Spread the love