C Programming language

adplus-dvertising
Integer and Float conversion in c
Previous Home Next

Integer and float conversion

In order to effectively develop C programs, it will be necessary to understand the rules that are used for the implicit conversion of floating point and integer values in C. These are mentioned below:

  1. An arithmetic operation between an integer and integer always yields an integer result.
  2. An operation between a real and real always yields a real result.
  3. An operation between an integer and real always yields a real result. In this operation the integer is first promoted to a real and then the operation is performed. Hence the result is real.

Example

Operation Result
5/22
5.0/22.5

Type conversion in assignment

It may so happen that the type of the expression and the type of the variable on the left-hand side of the assignment operator may not be same.In such a case the value of the expression is promoted or demoted depending on the type of the variable on left-hand side of =.

For example, consider the following assignment statements.

int i ;
float b ;
i = 3.5 ;
b = 30 ;

Here in the first assignment statement though the expression's value is a float (3.5) it cannot be stored in i since it is an int. In such a case the float is demoted to an int and then its value is stored. Hence what gets stored in i is 3. Exactly opposite happens in the next statement. Here, 30 is promoted to 30.000000 and then stored in b, since b being a float variable cannot hold anything except a float value.

Instead of a simple expression used in the above examples if a complex expression occurs, still the same rules apply. For example, consider the following program fragment:

float a, b, c ;
int s ;
s = a * b * c / 100 + 32 / 4 - 3 * 1.1 ;

Here, in the assignment statement some operands are ints whereas others are floats. As we know, during evaluation of the expression the int would be promoted to floats and the result of the expression would be a float. But when this float value is assigned to s it is again demoted to an int and then stored in s.

Previous Home Next