TYPE CONVERSION (or) CASTING - C-Tutorial

Latest

Saturday, 19 November 2016

TYPE CONVERSION (or) CASTING

TYPE CONVERSION (or) CASTING


The process of converting data item from one data type to another data type is called type casting.
Conversion rank procedure is:

Type casting can be classified into two types as:

1. Implicit Type Casting
2. Explicit Type Casting


1. Implicit Type Casting: If the operands are of different data types, the lower data type is automatically converted into the higher data type by the compiler before the operation proceeds.  Such conversion is known as implicit type casting.  Implicit type casting is also known as automatic type conversion.
In implicit type casting, the result is in higher data type and there is no loss of data.

Example: int i,j;
float p;
double d,r;
r= i*j + p/j +  p*d;
int*int + float/int + float *double
int + float + double
float + double
double

2.  Explicit Type Casting: Users can also be convert the data items from one data type to another data type.  Such conversion is known as explicit type casting.

For explicit type casting, the target data type placed within in parenthesis before the data item.

The general format of explicit type casting is:

Syntax: (TargetDataType) Expression;

Here,
Expression may be a constant, variable, or any expression.

In explicit type casting, there may be a loss of data which converting from higher data type into lower data types.

Example:

int x=14, y=3;
float z;

z = x/y; z = (float) x/y;

z = 14/3; z = 14.000000/3;
z = 4.000000; z = 4.666667

/* EXAMPLE PROGRAM FOR TYPE CASTING */

#include<stdio.h>
#include<conio.h>
main()
{
int x,y,z,total;
float avg;
clrscr();
printf("\nEnter Three Values:");
scanf("%d%d%d",&x,&y,&z);
total=x+y+z;
avg=(float)total/3;
printf("\nAverage Result:%f",avg);
}

No comments:

Post a Comment