Thursday 18 December 2014

Type Conversion/ Type Casting

Q. What is Type Conversion, how and when it happens?
Ans. When we write an expression in any language it would have some operators and operands. When there are two different types of operands (like: int and float) along with an operator(like: + or * etc.) then the operands are converted to a common type according to some rules( specifically in C ).

Example:
long int j=100000000000;
int i=10;
long int k=i+j;

then the value of i is automatically converted in to long for evaluating the expression and result will be long int. 
Note: the value of i is still 10 and type of i is still int. It just change the value of i to the long int temporarily for the expression evaluation.

      This conversion is called type conversion. It is happening by default automatically so it is called automatic type conversion. Which converts the "narrower range(like int)" operand to a "wider range (like long int)" operator. In this type of conversion no information is lost.

     We can forcefully convert any "wider range operand" to a "narrower range operand". The compiler will not give an error. But there is always a drawback of losing information in this type of conversion.
Ex: 
long int j=100000000000;
int i=(int) j;  /// type casting , converting value of j in to range of integer.

in this type of code compiler may not give an error but the value of i will not be equal to the value of j because j is containing value which is beyond the range of the integer variable. It is called type casting.

General Rules for automatic conversion( in C):
1. If one of the operand is long double, other will be converted to the long double.
2. Else if one of the operand is double, other will be converted to the double.
3. Else if one of the operand is float, other will be converted to the float.
4 .Else char and short int is converted in to int.

5. Then, if either operand is long, other will be converted in to long.

Note: So while doing type casting on your own always take care of not converting a wider range operand to a narrower range operand. Otherwise some information may be lost.
 Type conversion can be done while calling a function also.
Ex:
int m=10;
sqrt((double)m);

The in build function sqrt of the math.h library expect a double argument to it. If we want to find sqrt of an int then we can convert it to double while calling function. The value is converted to double and then send to the function.

Note: Again the value and the type of the m is still not changed.

 Stay tuned for the new posts and leave comment or ask questions if u have any :)


No comments:

Post a Comment

Related Posts

Related Posts Plugin for WordPress, Blogger...