C++ what is casting and why it is not a safe method?

Casting in C or C++ means converting one data type to another.Suppose you want to convert integer type to float type then casting will be performed.You can perform casting for built-in data types or some other type.In C and C++ there are two type of casting:

i)Implicit casting
ii)Explicit casting


Implicit casting

This type of casting does not make use of any standard library function.In this method to cast a value simply assign one data type value to another type.For instance if you want to convert float type to int type you can simply assign the float variable to int variable.Another way to convert float to int type is to mentioned the type to which the variable is converted to before the variable name.Look at the code below.

#include <iostream>

using namespace std ;

int main( )
{
float f=89.7658 , f1=67.89;

int i , ii , iii;

i=f ; //float f value converted to int type

/** The method shown below also works fine ***/

ii=(int)f1; //The type is mentioned
iii=int(f1); //this also works fine same as above

cout<< i << endl
    << ii << endl ;

cin.get() ;
return 0 ;
} 

Output,

89 67

For C programmer a code example is given below

float f=89.7658 ;
int i=int(f) , //Casting is performed;

ii=f ; //also works fine :data type not mentioned

printf( “%i %i” , i , ii ); 

Output,

89 89

The three methods of casting employed above are known as implicit casting.The two methods in which we mentioned the type to which the data is to be converted is known as C type casting,because it is originally part of C language.


ii)Explicit casting

Explicit casting make use of some standard functions to convert one type to another.There are four functions that can perform explicit casting:

a)static_cast
b)const_cast
c)reinterpret_cast and
d)dynamic_cast. (meant only for C++ user)

When to use each of these functions and what are their differences will be discussed thoroughly in Chapter 2.

The implicit and explicit casting method is shown briefly below.


Why casting is not a safe method?

Look at the code below.

long long ll=234235356767 ;
int i=int (ll) ; 

When ‘long long’ variable ‘ll’ whose size is 8 bytes,is converted to int type whose size is 4 bytes it results in some loss of information.This is due to the difference in the size of the two data types.

Link :Integer data type

However in some cases,even when the data type size are the same and casting is performed some values is still lost.Say converting float to int type (as shown in the Implicit casting type example above) the fractional part is lost hence the value losses it’s accuracy utterly.Due to this reason and another reason explained in Chapter 8 casting must be avoided as much as possible.




Leave a Reply

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