Wednesday, October 13, 2010

Type Casting in C Language

,

Type casting is a way to convert a variable from one data type to another data type. Type Casting is force to convert one data type to another data type. The process of such local conversion is known as casting a value. The general form of cast is: (type-name) expression where type-name is one of the standard C data types.

Consider, for example, the calculation of salary of employee to engineers in a town.

salary = amount / days

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

salary = (float) amount / days

The operator (float) converts the amount to floating point for the purpose of evaluation of the expression.


Example 
Action 
X=(int) 8.5  8.5 is converted to integer by truncation. 
A=(int) 21.3 / (int) 4.5  Evaluated as 21/4 and the result would be 5. 
B=(double) sum/n  Division is done in floating point mode. 
Y= (int) (a+b)  The result of a+b is converted to integer. 
Z= (int) a+b  a is converted to integer and then added to b. 
P=cos(( double)x)  Converts x to double before using it. 

0 comments to “Type Casting in C Language”

Post a Comment