blogger Indonesia

Follow judhyns blog

FORCED CONVERSION

Introduction

Forced conversion occurs when you are converting the value of the larger data type to the value of the smaller data type, for example, if the declaration is char c;

and you use the expression c = 300; Since the maximum possible value for c is 127, the value 300 cannot be accommodated in c. In such a case, the integer 300 is converted to char using forced conversion.

Program/Example

In general, forced conversion occurs in the following cases:

  1. When an expression gives a larger data type but the variable has a smaller data type.

  2. When a function is written using a smaller data type but you call the function by using larger data type. For example, in printf you specify %d, but you provide floating-point value.

Forced conversion is performed according to following rules:

  1. Normally, when floating points are converted to integers, truncation occurs. For example, 10.76 is converted to 10.

  2. When double is converted to float, the values are rounded or truncated, depending on implementation.

  3. When longer integers are converted to shorter ones, only the lower bits are preserved and high-order bits are skipped. For example, the bit representation of 300 is 1 0010 1100. If it is assigned to character, the lower bits are preserved since a character can have 8 bits. So you will get the number 0010 1100 (44 in decimal).

In the case of type conversion, lower data types are converted to higher data types, so it is better to a write a function using higher data types such as int or double even if you call the function with char or float. C provides built-in mathematical functions such as sqrt (square root) which take the argument as double data type. Suppose you want to call the function by using the integer variable ‘k’. You can call the function

sqrt((double) n) 

This is called type casting, that is, converting the data type explicitly. Here the value ‘k’ is properly converted to the double data type value.

Points to Remember

  1. C makes forced conversion when it converts from higher data type to lower data type.

  2. Forced conversion may decrease the precision or convert the value to one that doesn't have a relation with the original value.

  3. Type casting is the preferred method of forced conversion.

No comments:

feed

PR Check

activesearchresults

judhyn's blog

 

http://www.judhyn.blogspot.com | |