|
|
Tutorials

Cpp

|
Topic |
What is Type Casting in C++?
|
|
Explanation |
|
"Type Casting" is method using which a variable of one datatype is
converted to another datatype, to do it simple the datatype is specified using parenthesis in front of the value.
Example:
#include <iostream.h>
using namespace std;
int main()
{
short x=40;
int y;
y = (int)x;
cout << "Value of y is:: "<< y <<"\nSize is::"<< sizeof(y);
return 0;
}
|
Result:
Value of y is:: 40
Size is::4
In the above example the short data type value of x is type cast to
an integer data type, which occupies "4" bytes.
Type casting can also done using some typecast operators available in C++. following are
the typecast operators used in C++.
Example:
#include <iostream.h>
using namespace std;
int main()
{
int a = 31;
int b = 3;
float x = a/b;
float y = static_cast<float>(a)/b;
cout << "Output without static_cast = " << x << endl;
cout << "Output with static_cast = " << y << endl;
cout << "Type id of x = " << typeid(x).name() << '\n';
}
|
Result:
Output without static_cast = 10
Output with static_cast = 10.3333
Type id of x = float
In the above example we have assigned the integer variable "a" to be float using the static_cast operator. So
the result is "10.3333".
|
| Note |
C++ is one of the most used programming languages in the world. Also known as "C with Classes".
Hope you enjoy this tutorial. Do send your feedback or suggestions on this C++ tutorial. This is a copyright content.
|
|
|
|