Type conversions


Type conversions

 

Implicit or Automatic type conversion


C permits mixing of constants and variables of different types in an expression. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance. During evaluation, if the operands are of different types the lower type is automatically converted to the higher type before the  operation proceeds.
The result is of higher type. 
The following rules apply during evaluating expressions

All short and char are automatically converted to int then 
1. If one operand is long double, the other will be converted to long double and result will be
    long double. 
2. If one operand is double, the other will be converted to double and result will be double. 
3. If one operand is float, the other will be converted to float and result will be float. 
4. If one of the operand is unsigned long int, the other will be converted into unsigned 
    long int and result will be unsigned long int. 
5. If one operand is long int and other is unsigned int then 
    a. If unsigned int can be converted to long int, then unsigned int operand will be 
        converted as such and the result will be long int. 
    b. Else Both operands will be converted to unsigned long int and the result will be 
        unsigned long int. 
6. If one of the operand is long int, the other will be converted to long int and the result will        be
long int..
7. If one operand is unsigned int the other will be converted to unsigned int and the 
    result will be unsigned int.

(high) long double ->double -> float ->  unsigned long int -> long int -> unsigned int -> int  ->  short or char (low)
                       

Explicit Type conversion or Type Casting


Many times there may arise a situation where we want to force a type conversion in a way that is different from automatic conversion.
Consider for example the calculation of average of 3 numbers 
            int m1,m2,m3;
            float avg;
            avg=(m1+m2+m3) / 3;
            Since m1,m2 and m3 are declared as integers, the decimal part will be rounded off and its ratio will represent a wrong figure. i.e. for three set of values like (30,60,90), (31,60,90) and (32,60,90), the average will be 60.000000. This problem can be solved by converting locally one of the variables to the floating point as shown below.
avg= (float) (m1+m2+m3) / 3;

            The operator float converts the m1+m2+m3 expression into floating point for the purpose of evaluation of the expression. Then using the rule of automatic conversion, the division is performed by floating point mode, thus retaining the fractional part of the result. The process of such a local conversion is known as explicit conversion or casting a value.

The general form is
                                    (type_name) expression

No comments:

Post a Comment