C++ Type Casting

Type casting causes the program to treat a variable of one type such as an int to act like another type such as a char for one single operation. The implicit castings are automatically performed when value of a variable is copied to another variable of a compatible type.

Implicit Casting Example

#include <iostream>
using namespace std;
int main()
{

short distance = 24;
int milage;
milage = distance;
cout << “milage = ” << milage;
return 1;

}

In this example the value of distance is copied from ‘short’ to ‘int’ without using type cast operator.

C++ Type Casting

In c++ many conversions require an explicit conversion and a cast operator is used to force one data type to act like another. There is also a functional notation which can be used for type casting. The cast operator is unary and has the same precedence as other unary operators.

#include <iostream>
using namespace std;
int main()
{

double a = 41.63;
double b = 54.23;
int c, d;

c = (int) a;
cout << “Value of c = ” << c << endl ;

d = int(b);
cout << “Value of d = ” << d << endl ;
return 1;

}

Output

Value of c = 41
Value of d = 54

Leave a Reply

Your email address will not be published. Required fields are marked *