Implicit and Explicit type conversion
Type casting: Typecasting is used to convert the type of a variable, object, function or expression return types value to another value type. As we know the value of a variable is stored as a sequence of bits and the datatype of the variable tells the compiler that how to translate those bits into meaningful values. We often see that that data of one type needs to be converted into another type in a single program. This all is known as type casting. This is one of the said advantageous of C++ is the type-safe feature. During the compile or runtime, there is type checking process that is not available in C. This can avoid a lot of program bugs and unexpected logical errors.
Implicit type conversion:
It is done automatically by the compiler whenever data from different type is intermixed. When a value from one type is assigned to another type, the compiler implicitly converts the value into a value of the new type. For example:
double x = 30; // here implicit conversion to double value i.e 30.0
int y = 4.134; // here implicit conversion to integer value i.e 4
Program Code:
#include<iostream.h>
using namespace std;
int main()
{
double x=30;
int y = 4.134;
cout<< x<<endl;
cout<< y;
return 0;
}
Output:
30.0
4
Explicit type conversion:
It is done by the user when it is required by the program. In standard C++ programming, casts are done via the () operator, with the name of the type to cast to inside. For example:
int x = 16;
int y = 4;
float c = (float )x/y;
Program Code:
#include<iostream.h>
using namespace std;
int main()
{
int x = 16;
int y = 4;
float c = (float )x/y;
cout<< c;
return 0;
}
Output:
4.0
Thanks
Mukesh Rajput
Post A Comment:
0 comments: