Type casting in C


Type casting in C

Sometimes we required to force the compiler to explicitly convert the value of an expression
to a particular type.This would be clear from the below example :

#include <stdio.h>
#include <conio.h>

void main()
{
float a;
int x=6;
int y=4;

a=x/y;

printf("\nValue of a = %f",a);

getch();
}

The output will be :

Value of a=1.000000

The answer is 1.000000 and not 1.5. This is because x and y both are integer and hence
6/4 yields an integer=1. This 1 is stored and is converted into 1.000000 as the storing
variable (a) type is a float.

Solutions to this problem are:

1. Change the type int to float of any of the x or y variable or

2. Typecasting


Tpecasting :


Following example shows how to do typecasting :

void main()
{
float a;
int x=6;
int y=4;

a=(float)x/y;

printf("\nValue of a = %f",a);
}

Noe the output will be :

Value of a =1.500000

This program used typecasting in which we put float in paranthesis before the evaluating expression.

a=(float)x/y;

The expression (float) causes the variable x converted to type float from type int before
being used in division operation.

This was the concept of type casting.

     Prev                                                   NEXT

0 comments:

Post a Comment