Type Conversion of Data Types in C++

Type conversion simply means converting data from one data type to another. There are formally two types of type conversion – Implicit type conversion and explicit type conversion.

This article is written in context with C++, but these concepts can be applied to any programming language.

Implicit Type Conversion

Let’s look at some basic points about this type of conversion:
1. It is also known as ‘automatic type conversion’.
2. It is automatically done by compiler
3. It takes place when there are different data types used in a particular expression. Say for example,

    int i = 54;
    double d = 6.64;
    double d1 = d + i;

In cases like this, implicit type conversion occurs.
4. It is more of a type promotion. Data types of smaller size (range wise) are automatically converted to that of bigger size to avoid loss of information.
5. All the data types of the variables are upgraded to the data type of the variable with largest data type.
Rules of promotion,

       bool => char => short int => int => unsigned int => long => unsigned  long long => float => double => long double
  1. Sometimes, implicit conversion can create problems for us. They can result in loss of sign, when a signed int is promoted to an unsigned int. It can also result in loss of information, when a long long int in promoted to float.

Let's see an example to understand it better.

#include <iostream>
using namespace std;
int main()
    int x = 10;    // integer x
    char y = 'a';  // character c

    // y implicitly converted to int. ASCII
    // value of 'a' is 97
    x = x + y;

    // x is implicitly converted to float
    float z = x + 1.0;

    cout<<"x = "<<x<<endl;
    cout<<"z = "<<z<<endl;
    return 0;

Output of the above program is
x = 107, z = 108.000000

Explicit Type Conversion

Now let’s look at some basic points about this type of conversion:
1. It is also known as ‘type casting’.
2. It is not automatically done by compiler, rather it is user defined i.e. explicitly done by user.
3. Any type can be explicitly converted to any other data type, but we should be careful while doing this otherwise problems like data loss and overflow can occur.

The syntax in C++:
(type) expression
type indicated the data type to which the final result is converted.

As we know the best way of understanding, examples!

#include <iostream>
using namespace std;
int main()
    double x = 1.2;

    // Explicit conversion from double to int
    int sum = (int)x + 1;

    cout<<"sum = "<<sum;
    return 0;

Output of the above program is
sum = 2

In this article, we saw type conversions of both types. Implicit and explicit. These concepts come in very handy when we work on data with mixed data types.



Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?