Type Conversion in C programming Language with example program
Program to understand type conversion in C Language :
In this program, We are going to look at the Type Conversion in C language.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/* Program to understand type conversion in C Language */ #include<stdio.h> int main(void) { char c1, c2; int i1, i2; float f1, f2; c1 = 'H'; i1 = 80.56; /* float converted to int, only 80 assigned to i1 */ /* You will get Warning like below. warning: implicit conversion from 'double' to 'int' changes value from 80.56 to 80 */ f1 = 12.6; c2 = i1; /* int converted to char */ i2 = f1; /* float converted to int */ /* Now c2 has the character with ASCII value 80, i2 is assigned value 12 */ printf("c2=%c, i2=%d \n", c2, i2); f2 = i1; /* int converted to float*/ i2 = c1; /* char converted to int */ /* Now i2 contains ASCII value of character 'H' which is 72 */ printf("f2=%.2f, i2=%d \n", f2, i2); return 0; } |
Type conversion in C Program Output:
1 2 3 4 5 6 7 8 9 10 11 |
$ gcc type-casting.c type-casting.c:10:10: warning: implicit conversion from 'double' to 'int' changes value from 80.56 to 80 [-Wliteral-conversion] i1 = 80.56; /* float converted to int, only 80 assigned to i1 */ ~ ^~~~~ 1 warning generated. $ $ ./a.out c2=P, i2=12 f2=80.00, i2=72 $ |
Program Explanation:
As you can see from the comments in the above program, There are a lot of implicit type conversions in the program.
Like variable i1 value implicitly converting from the float value to int value.
C Language does implicit type casting to fit the values into the target variable. For example,
int i1 = 80.56;
Here the target variable i1 is an integer, So C language is implicitly converted the float value 80.56 to 80 and assigned to the variable i1.
C language also supports the explicit type conversion, Where we need to specify the compiler to covert the value from one datatype to another datatype. There are cases, where we need to explicitly perform the type conversions. We are going to discuss them in the upcoming articles.
1 Response
[…] C Program to understand Type Conversion […]