This chapter introduces typecasting in C progamming language. As the name suggests it casts the type. This is a very simple topic where there is a need to convert one data type to another. Sometimes we have scenario’s where compiler is forced to convert one data type to another and this is possible by type casting. So we manipulate the nature of data stored in variable and this procedure is also known as data type conversion. For example, we have variables of type integer (int) but after applying an arithmetic operation, say division the result is of float type, in such cases we need type conversion or typecasting.
Format of type conversion is as follows:
(data_type) variable_name;
Explanation: Here,
data_type is the desires data type
variable_name is the name of variable of data_type
Let us consider an example so that it becomes easier for us to understand the concept.
/* Program to demonstrate typecasting in C */
# include <stdio.h> # include <conio.h> # include <stdlib.h> # include <math.h> void main() { clrscr(); float x; int y,z; int w; printf("\n Enter the value of y \n"); scanf("%d" &y); printf(" Enter the value of z\n"); scanf("%d", &z); printf(" Values of y and z are: \n"); printf("y=%d\n", y); printf("z=%d\n", z); x= (float) y/z; printf("After typecasting the value of y/z =%f\n", x); w=y/z; printf("Without typecasting the value of y/z=%d\n", w); getch(); }
Program will look similar in editor as shown in the following snapshot:
Figure - Snapshot of program to demonstrate typecasting in C
After compiling program looks similar as in following snapshot:
Figure - After compiling the program to demonstrate typecasting in C