Type Casting in C Programming Language with Examples

What is Type Casting in C?
Type Casting is a method to convert the data type of a variable or value to another data type.Classification of Type Casting
Type Casting is mainly two types: Implicit and Explicit Type Casting.
Implicit Type Casting
Implicit Type Casting is performed by the compiler itself. Programmer doesn't
require to define type casting operation. The advantage of this casting is
there is no loss in data manipulation.
Example: The following program performs implicit type casting. Because
variable x and y are different size variables.
#include <stdio.h>
int main() {
short int x = 9;
int y = 2;
printf("%d\n", x + y);
printf("Size of x = %d\n", sizeof(x));
printf("Size of y = %d\n", sizeof(y));
printf("Size of x + y = %d\n", sizeof(x+y));
return 0;
}
Output:
11 Size of x = 2 Size of y = 4 Size of x + y = 4
Explicit Type Casting
Explicit Type Casting is performed by the programmer. Programmer requires to
define type casting operation. The disadvantage of this casting is there is
loss in data manipulation.
Example: The following program performs the explicit type casting.
#include <stdio.h>
int main() {
int x = 9, y = 2;
float z;
z = (float) x / 2;
printf("%.2f\n", z);
return 0;
}
4.50
Now check the following program and its output to understand differences for performing different explicit casting.
#include <stdio.h>
int main() {
int x = 9, y = 2;
printf("%d\n", x/y);
printf("%.2f\n", x/y);
printf("%.2f\n", (float)x/y);
printf("%.2f\n", (float)(x/y));
printf("%.2f\n", x/(float)y);
printf("%.2f\n", (float)x/(float)y);
printf("%d\n", (float)x/y);
return 0;
}
Output:
4 0.00 4.50 4.00 4.50 4.50 -1417850208