Implicit and explicit is a type conversion which helps converting an expression of a given type into another type. In general, type conversion involve converting a narrow type to the wider types so that loss of information is avoid. It has two type i.e. is automatic conversion and type casting.
What is implicit type conversion?
Automatic conversion is also called the implicit type conversion. When two operands of different type are encountered in the same expression, the lower type variable is converted to the type of the higher type variable by the compiler automatically. This type of conversion is automatically done by the compiler at the time of a compilation.
Example of implicit or automatic conversion
float x;
int a;
double b;
long double l;
the automatic type conversion of the expression b*a/1+x is illustrate in following table.
Expression | Operand1 | Operand2 | Result |
b*a | double | int | double |
b*a/1 | double | long double | long double |
b*a/1+x | long double | float | long double |
What is explicit conversion in c++ ?
Sometimes, a program needs to convert a value from one tab to another in a situation where the compiler will not do it automatically. This is the forceful conversion from one type to another type. To perform a cast, following syntax is used (data type) expression;
Example of explicit or type conversion in c++
a is int type and it is needed to be converted into float type then:
intp;
(float)a; /*a will be converted into float type */
the value of a wiil remain unchange but type will be change. for example if value of a=10 then after cast its value will be 10.0. some examples of type casts and their action are given below.
Expression | Action |
a= (int) 6.5 | 6.5 is convert to integer by truncation |
b=(int) 6.5/(int) 6 | Evaluated 6.5/6 and result is 1 |
x=(int) a+b | the result of a+b is convert to integer |
m=(double) sum/n | division is floating point mode |
Program to show Implicit and explicit type conversion in c++ to get fractional result from division of two integers.
#include<iostream>
#include<conio.h>
#include<iomanip.h>
using namespace std;
int main()
{
int x,y;
float z;
cout<<"enter teo numbers"<<endl;
cin>>x>>y;
z=x/y;
cout<<"result of division without casting="<<setprecision(2)<<z<<endl;
z=float(x)/y;
cout<<"result of division with casting="<<setprecision(2)<<z<<endl;
getch();
return 0;
}
Output
Enter two number
14
3
Result of division without casting =4
Result of division with casting =4.66
your explained is wonderfull..nice to meet you sir