In this post, I wanted to note down one of the most important fundamentals of any programming language, which is ' Type Casting '.
Type Casting? Why is this important?
Whenever we program, we'll have to store data. In order to do that there're :
Variables - "Physical location of Memory that allows to store data as sequence of bits & tells the compiler how to translate them into meaningful values"
But, sometimes you may end up having multiple types of operands to be operated with operators.
There are 2 basic Type Conversions.
- Implicit Type Conversion
- Explicit Type Conversion
Look at the following C++ Example. This is what we call Implicit (Automatic/Widening) Type Conversion where, you store int inside double. This is similar to : Ant inside Elephant.
#include<iostream>
using namespace std;
int main()
{
double count = 7;
cout<<" output "<<count<<endl;
return 0;
}
But, can we perform the other way around. Elephant inside Ant.
#include<iostream>
using namespace std;
int main()
{
int count = 7.98;
cout<<" output "<<count<<endl;
return 0;
}
According to C++ variable types,
Storing value of 7.98 a double value inside int may look like stupid. But, Automatic Type Conversion of C++ allows us to do this & the program compiles & runs without any problem at all. But, we lose precision & unsafe results are possible. To avoid this happening We can use C++ Explicit Type Casting (Narrowing).
double d=22.321;
int i = (int)d;
OR
double d=22.321;
int i = int(d);
Otherwise, we can try using static_cast of C++.
double d = 23.321;
int i = static_cast<int>(d);

No comments:
Post a Comment