Type casting C

We have seen that compiler causes internal type conversion automatically when it has to handle operands of different type.
There is also provision for programmer to explicitly convert value of an expression into a different data type. To do so, expression must be preceded by name of desire data type enclosed in parenthesis.

(data-type) expression;

This is called type casting done with a unary operator cast.
E.g

main ( )
{
int x = 6, y = 4;
float a;
a = x / y;
}

The expression x/y will cause integer division (i.e. decimal part will be truncated) giving result 1. It will then be converted to float (1.00) since it is to be assigned to “a” which is a float.
But if we want that the result should not be truncated and some other factors don’t allow us to define x as float then we can use type casting.

main ( )
{
int x = 6, y = 4;
float a;
a = (float) x / y;
printf (“\nX = %d”, x);
}

The float(x), converts x into a floating point value before performing the division so that result is floating point. The conversion produces x into proper type. The value of x is not changed permanently as seen from the printf statement that follows.
Another example can be given as a function ‘sqrt’ which takes double as argument and would give nonsense results if some other type of data is given.

int x;
double y;
y = sqrt (double (x) );

x is converted to type double.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C Topics