Type Conversion in C++

Type conversion is basically converting one data type to another data type. Type Conversion is of two types.

  • Implicit Type Conversion 
  • Explicit Type Conversion

Implicit Type Conversion:

  • It is also known as the Automatic Type Conversion.
  • The compiler automatically converts one data type into another data type based on their Preferences. The user has nothing to do with it.
  • Implicit Type Conversion occurs when the expression has multiple data types.
  • Here is the priority order of the data types.
bool < char < short int < int < unsigned int < long < unsigned long long < float < double < long double

 Implicit Conversion Example:

Example 1:

Code:

C++ Code

#include <bits/stdc++.h>

using namespace std;

int main()

{
  int x = 3;
  char y = 'a';
  if (x < y)
    cout << "y is greater than x" << endl;
  else
    cout << "x is greater than y" << endl;
  return 0;
} 

Output: y is greater than x

Explanation : 

x is of ‘int’ data type y is of ‘char’ data type. In the expression x < y, two different data types are being compared. A comparison is done between two different data types, so the compiler converts the low priority data type into a higher priority data type. ‘Char’ has low priority so it is converted into ‘int’ data type i.e ASCII of ‘a’. So the comparison is 3 < 97 (since ASCII of ‘a’ is 97).

Example 2:

Code:

C++ Code

#include <bits/stdc++.h>
using namespace std;

int main()

{
    int x = 3;
    float y = 5.45;
    cout << x + y << endl;
} 

Output : 

8.45

Explanation: 

x is of ‘int’ data type and y is ‘float’ data type. In expression x+y, two different data types are being added, so the compiler converts the lower priority data type into a higher priority data type. As float has higher priority compared to int, x is converted to float and added to y. So the output is float.

Explicit Conversion: 

It is user-defined. It is called Typecasting. User type casts one data type to the desired data type.

The syntax for Type Casting :

Typecasting is done by explicitly defining the data type desired in front of the current data type variable in parenthesis.

(desired data type) current data type variable

Example 1:

Code:

C++ Code

#include <bits/stdc++.h>
using namespace std;

int main()

{
    int x = 98;
    cout << char(98) << endl;
} 

Output: b

Explanation: Using type conversion x is converted into a char data type. Char corresponding to ASCII value 98 is b. So the output is b.

Example 2:

Code:

C++ Code

#include <bits/stdc++.h>
using namespace std;

int main()

{
    float x = 5.3455;
    cout << int(x) << endl;
    return 0;
} 

Output: 5

Explanation: Using type conversion x which is a float data type is converted into an int data type. Int value of 5.3455 is 5. So the output is 5.

Special thanks to SaiSri Angajala for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article