Friday, February 5, 2010

What is Typecasting? Explain with examples.


Typecasting: C++ is very strict about type compatibility. Different variable types must be cast when their values are assigned to each other. Type cast operator is used for explicit type conversion of variables. A type name behaves as if it is a function for converting values to a designated type.
E.g. average = sum/float(i);
The variable ‘i’ is converted to float and used to calculate the average.

Explain typecasting.

Answer - Typecasting enables data type conversion. C++ supports Implicit conversions and Explicit conversion. Implicit conversions automatically performed when a value is copied to a compatible type. If there is an operation between an int and a float, the int is promoted to float before performing operation.
You can cast types explicitly as follows. 
int i, j, k; 
k = i * long(j);

0 Comments: