What is type-casting in C++?

Type-casting

Suppose we want to change an int data type to a char data type. This is where type-casting comes into play.

Type-casting* is the conversion of one data type into another.

There are two ways to perform type-casting in C++:

  • Implicit Casting
  • Explicit Casting
Types of casting in C++

Let’s discuss them one by one.

Implicit casting

In implicit casting, the compiler will convert the values automatically. The conversion takes place in the order of precedence, i.e., the data type is converted into a data type of higher precedence. It also ensures a minimum loss of data. Below is the precedence order of the data types.

For example, if we take an expression where we are performing some operation on an int and float data type, the int value will automatically be converted to a float data type due to its higher precedence.

Order of precedence of data types in C++

To better understand, take a look at the code snippet below.

#include <iostream>
using namespace std;
int main() {
int a = 18;
char b = 'S';
a = a * b;
float c = a / 5.0;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
return 0;
}

Explanation:

  • In line 1, we import the required header file.

  • In lines 5 and 6, we define an integer and character variable and assign values to them.

  • In line 7, we perform multiplication between an integer value and character value. Here, b is implicitly converted to its ASCII value by the compiler.

  • In line 8, we perform division between an integer and float value. Here, a is implicitly converted to float due to its higher precedence.

Now, let’s discuss explicit casting.

Explicit casting

In explicit casting, the user needs to physically convert one data type into another. The syntax for using this casting is:

(data_type) variable_name;

To better understand, take a look at the code snippet below.

#include <iostream>
using namespace std;
int main() {
float x = 28.5;
float a = (int) x - 12;
cout << "a = " << a;
return 0;
}

Explanation:

  • In line 5, we define a float variable and assign a value to it.
  • In line 6, we have explicitly converted the value from float to int and performed the subtraction operation. Once we explicitly convert the value from float to int, it will take the 28 (instead of 28.5) and then subtract it with 12, resulting in an integer value 16.

In this way, we can use implicit and explicit casting depending on our needs.