ProAnswers.org

When should a type cast be used in C?

Cast Operator ->>
Cast operator is an operator which is a signal to compiler to convert
data from one type to another.

format:-   (type_name)Expression

1) type_name is one of the standard data type available.
2) Expression may be a constt, variable or expression.

Example:  ratio = (float)no of girls/no of boys

Types:- 2 types are there of type cast operator:

a) [b]Automatic(Implicitly):-[/b]
                          This type of casting automatically done by compiler. If the
operands are of diffrent types,the lower type is automatically converted to the higher
type before the operation proceds.

for example:

#include
#include
void main()
{
  clrscr();
  int a=4;
  float b;
  b=a;                     // automaticaly casting done by compiler
  printf("%f",b);
  getch();
 }
Output will be 4.000000 because b is float type

b) [b]Explicitly :[/b]
                  This type of casting done by force not by the compiler. If the
operands are of diffrent types,the Higher type is  converted to the lower
type before the operation proceds by force.

for example :- if we dolike this:

#include
#include
void main()
{
  clrscr();
  int a=8,b=3;
  float c;
  c=a/b;                     
  printf("%f",c);
  getch();
 }
 
 Output willbe 2.000000 which is Incorrect.

 now we go with Explicitly casting

 #include
 #include
 void main()
 {
  clrscr();
  int a=8,b=3;
  float c;
  c=(float)a/b;        // Explicitly  here a temporarly  converted or casted to float            
  printf("%f",c);
  getch();
 }

 Output willbe 2.666667 which is Correct.

 [b]When to use :[/b]

 1) Type casting is used when you want to convert the value of one data type to another.
 2)One use for typecasting for is when you want to use the ASCII characters. For example, what if you want to create your own chart of all 256 ASCII characters. To do   this, you will need to use to typecast to allow you to print out the integer as its character equivalent.

 [b]Important Points:[/b]

 1) Type casting does not change the actual value of variable, but the resultant   value may be put in temprory storage
 2) Type casting is done using a cast operator that is also a unary operator