Typecasting in C
Typecasting: It is a data type is converted into another data type by the programmer using the casting operator during the program design. In typecasting, the destination data type may be smaller than the source data type when converting the data type to another data type, that’s why it is also called narrowing conversion.
There are some cases where if the datatype remains unchanged, it can give incorrect output. In such cases, typecasting can help to get correct output and reduce the time of compilation.
Below is the C program to illustrate the need for typecasting:
The result is 7.000000
Explanation: Here, the actual output needed is 7.500000, but the result is 7.000000. So to get the correct output one way is to change the data type of a given variable. But correct output can also be done by typecasting. This consists of putting a pair of parentheses around the name of the data type like division = (float) a/b.
Below is the C program to showcase the use of typecasting:
The result is 7.500000
Explanation: In the above C program, the expression (float) converts variable a from type int to type float before the operation.