Tuesday, November 1, 2011

Type-cast operator

The type cast operator is very important in C. Cast operator uses in convert one data type to another data types. Type casting may be two types:
  1. Implicit type cast
  2. Explicit type cast
Implicit type cast

In C, implicit type cast are automatically handled by compiler i.e. when two or more data types are getting execution then the final data-type will be that data type as it is declared, i.e it is not depend on conversion of data type.
It is clear understand by example as:

 #include<stdio.h>
 #include<conio.h>
 void main()
 {
  int i,j;
  float f;
  double d;
  i=d*f+f*j;
 }

what you think, what will be data type of i?
it is double!! No, right answer is int. You see in program that double has high priority or  precedence of float and int, so result of data type will be comes in double but when result is assign in i, it will be convert in int because i is declared as int. It is implicit type casting.

Explicit type cast

An explicit type cast is a cast that we should specify invoke with either the cast. The compiler does not automatically invoke to resolve the data type conversion.
Let's understand explicit with example:

/*A student marks of three subject as m1,m2,m3 and calculate percentage(per)*/
#include<stdio.h>
#include<conio.h>
void main()
{
 int m1=70,m2=70,m3=100,total;
 float per;
 total=m1+m2+m3;
 per=total/300*100;
 printf("%f",per);
}
output:- 0.000000

Surprise, let's explain to me, it is a common type cast mistake, look at per=total/300*100; statement. In this statement first of all total/300 will be solve so total(240) and 300 are int hence 240/300 will be produce a float value so result is 0.000000. These mistake may me solved by three ways as:

1. We mention type cast in above program as:
 /*demonstration of type casting*/

 #include<stdio.h>
 #include<conio.h>
 void main()
 {
  int m1=70,m2=70,m3=100,total;
  float per;
  total=m1+m2+m3;
  per=(float)total/300*100;
  printf("%f",per);
 }

 output:- 80.000000


2. We used total as float variable.
 #include<stdio.h>
 #include<conio.h>
 void main()
 {
  int m1=70,m2=70,m3=100;
  float per,total;
  total=m1+m2+m3;
  per=total/300*100;
  printf("%f",per);
 }

 output:- 80.000000


3. we convert int to float to the 300 by adding decimal portion.
 #include<stdio.h>
 #include<conio.h>
 void main()
 {
  int m1=70,m2=70,m3=100,total;
  float per;
  total=m1+m2+m3;
  per=total/300.0*100;
  printf("%f",per);
 }

 output:- 80.000000


No comments:

Post a Comment