Convert data types in C++ (Implicit ways)

Type convertion is a very common in programming. Let’s see ways to solve this issue in C++: implicit and explicit ways. In this entry we will take a look at implicit ways.

Implicit ways

Normal types

It is likely automatical conversion. Something is like promotion when int type is converted to float or double type, char to int, short to int or long. By this type of conversion value of variables is not be lost. For example: 6 -> 6.0. or ‘c’->”c” [see the following example]

#include<iostream>
using namespace std;
int main(){
    int var1(6);
    char var2('a');
    double var1_1(var1);
    int var2_1(var2);
    cout<<var1_1<<endl;
    cout<<var2_1<<endl;
}

The output is:

6
97

However if two types are not compatible original values can be lost, e.g. in case convert form int to unsigned, or double to int [see the following example].

#include<iostream>
using namespace std;
int main(){
    double var1(6.5);
    int var2(-1);
    int var1_1(var1);
    unsigned var2_1(var2);
    cout<<var1_1<<endl;
    cout<<var1_2<<endl; } 

The output is:

6 4294967295

Form 6.5, it leaves 0.5 to be an integer and becomes 6. As for -1, it become the largest unsigned integer (4 bytes – 1 byte is 8 bits)-> 2^32-1= 4294967296-1=4294967295.

Pointers

I wonder if a pointer of int can be converted to a pointer of double? Let’s give it a go.

The answer is no, we can’t. There is an error prompt of the following code:

#include<iostream>
using namespace std;
int main(){
    int var1(6);
    int* p_var1=&amp;amp;amp;var1;
    double* var1_1;
    var1_1=p_var1;
    cout<<*var1_1<<endl;
}

 

error: cannot convert 'int*' to 'double*' in assignment|

As for pointers, there are two important types of them is NULL POINTER and VOID POINTER.

NULL POINTER POINTS TO “NOWHERE” WHILE VOID POINTER POINTS TO “SOMEWHERE” WITHOUT SPECIFYING DATA THAT ADDRESS CONTAINS.

As for converting pointer types, there are some rules to consider:

  1. Null pointer can be converted to any pointer types
  2. Pointer to any type can be converted to void pointer.

Let’s see some illustrations of the above rules:

#include<iostream>
using namespace std;
int main(){
    int* p1=nullptr;
    double* p2=nullptr;
    int var1=5;
    double var2=5.5;
    p1=&var1;
    p2=&var2;
    cout<<"address of var1="<<p1<<"\tvalue of var="<<*p1<<endl;
    cout<<"address of var2="<<p2<<"\tvalue of var="<<*p2<<endl;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s