Converting any variable datatype into another datatype is called as type casting.
It is best to do type casting to avoid data loss.
Syntax for type casting
1 |
(new_data_type_name) expression; |
Two types of typecasting are:
- implicit typecasting
- explicit typecasting
Implicit typecasting:
Implicit typecasting is handled automatically by the compiler. Following example shows how implicit typecasting works-
1 2 3 4 5 6 7 8 |
void main() { int a=5; int b=2; float c; c = a/b; printf("%f",c); } |
Output: 2.0
The actual output of a/b is 2.5. But in C language int/int (integer/integer) will give an integer as an output.
So 0.5 get truncated. Therefore output is 2.
Value 2 is stored in c variable as a float number i.e c = 2.0 since c is a variable of type float. In this way compiler does this typecasting implicitly.
Explicit typecasting:
Explicit typecasting is done explicitly done by the programmer. Following example shows the explicit typecasting done by user-
1 2 3 4 5 6 7 8 |
void main() { int a=5; int b=2; float c; c = (float)a/b; printf("%f",c); } |
Output: 2.5
The ‘(float)a’ convert ‘a’ into float value before division. So temporary, for time being, ‘int a’ gets converted into a float for this expressions only.
Here ‘float/int’ will give value in floating number, therefore, numbers won’t get truncated.
Therefore output is 2.5.
Program illustrate typecasting:
Write a program to accept marks of 5 subjects from the user and calculate their average. Use implicit and explicit typecasting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include<stdio.h> int main() { int sub1, sub2, sub3; float average; printf("Enter the marks of 5 subject\n"); scanf("%d %d %d",&sub1,&sub2,&sub3); average = ((sub1 + sub2 + sub3) / 3); //implicit typecasting printf("\nAverage of implicit typecasting = %f",average); average = (float)(sub1 + sub2 + sub3) / 3; //explicit typecasting printf("\nAverage of explicit typecasting = %f",average); } |
Output:
1 2 3 4 5 6 |
Enter the marks of 5 subject 40 50 70 Average of implicit typecasting = 53.00 Average of explicit typecasting = 53.33 |