Implicit And Explicit Type Conversion
Implicit And Explicit Type Conversion
The type conversion is the conversion of a variable data type from one to another.
suppose we are adding two numbers one integer and the other floating point number for Example:- 2 + 3.5, the answer will be 5.5, what we have done here is we know that 2 can also be written as 2.0 and then we perform the addition with 3.5 and we get the answer 5.5.
The same thing happens in the C++, the compiler knows that 2 which is integer and the 3.5 which is floating point number so it will automatically convert the 2 which is an integer type into float and then perform the addition. This is known as implicit type conversion, the implicit type conversion is the conversion that takes place automatically by the compiler.
You might be thinking that why does the compiler not convert the number 3.5 in to floating point number? write. in the above example you might not have the question 🙋 , but in the following case you would definitely have the question, 2.0 + 1 in the normal mathematics the answer will be 3 or 3.0 we can ignore the zero after the decimal point, but this can not be done with the C++, C++ compiler will still convert the 1 in to 1.0 and then perform the addition.
This is because in C++ the implicit type conversion takes place in a particular order of the datatypes which is shown in the bellow figure.
The above image shows that the datatypes on the top can be converted to the bellow datatypes only, the bottom datatypes can not be converted to its above datatypes.
Explicit type conversion:
Some times we require a certain datatype only to work with, for example their is an function that return which takes an float, and int arguments and return an integer, this function is performing the addition of the two numbers i.e. float number and int number, but the implicit conversion will convert the int to float, but we need float to convert to int so in this case will have to use explicit type conversion, the explicit type conversion is nothing but the conversion done by the user forcefully which it would normally not do. this can be done in 2 ways, and both of them works
- (type-name) expression // C notation
- type-name(expression) // C++ notation
Example:
#include<iostream> using namespace std; int main(){ int x = 10; float y = 20.22; cout << "int x = " << x; cout << "\nfloat y = " << y; cout << "\nfloat(x) = " << float(x); cout << "\n(float)x = " << (float)x; cout << "\nint(y) = " << int(y); cout << "\n(int)y = " << (int)y; return 0; }
output:
int x = 10
float y = 20.22
float(x) = 10
(float)x = 10
int(y) = 20
(itn)y = 20
Comments
Post a Comment
if you have any doubts, let me know