Explain explicit type conversion in C Language while evaluating expressions with examples?

Explicit Casting

There are instances when we want to force a type conversion in a way that is different form the automatic conversion. For example, the calculate of ratio of females to males in a town is,


  ratio = female_number / male_number

Since female_number and male_number are declared as integers in the program, the decimal part of the result of the division would be lost and ration would represent a wrong figure. This problem can be solved by converting locally one of the variables to the floating point as shown below:


 ratio = (float) female_number / male_number

The operator (float) converts the female_number to floating point for the purpose of evaluation of the expression. Then using the rule of automatic conversion, the division is performed in floating point mode, thus retaining the fractional part of result.

We can note that the operator (float) does not affect the value of the variable female number. Also, the type of female_number remains as int in the other parts of the program.
The general form of a cast is :


 (type - name) expression

Where type-name is one of the standard C data types.

The expression may be a constant, variable or an expression.
Casting can be used to round - ff a given value.

 x = (int) (y + 0.5);

if y is 27.6, y + 0.5 is 28.1 and on casting, the result becomes 28, the value that is assigned to x.
When the higher type of data is converted into lower type data, then its value may be truncated.


Example - 1:
   int i ;
   double k = 4.5350;
   i = k;

Now the variable i consists of 4. The remaining data gets truncated. This process is also called narrowing.

Example - 2 : Program using explicit type casting


 #include <stdio.h>
 main()
 {
  int a = 123;
  float b = 1.234;
  double c = 12456.123456789;
  long double d = 12345678.123456789123;
  printf("The value of integer a in float is %f \n", (float) a);
  printf("The value of float b in int is %d \n", (int) b);
  printf("The value of double c in int is %d \n", (int) c);
  printf("The value of float c in double is %lf \n", (double) b);
  printf("The value of long double c in int is %d \n", (int) d);
 }

Output : 

 The value of integer a in float is 12.000000
 The value of float b in int is 1
 The value of double c in int is 12456
 The value of float b in double is 1.234000
 The value of long double c in int is 24910

In the last statement, long double will be first converted in to integer.
The integer value is 12345678, it exceeds the integer range. The value 12345678 will be converted to 24910, which is within the integer range.

Post a Comment

0 Comments