C Tutorial/Data Type/Data Type Cast
Data type cast: from int to float
<source lang="cpp">#include <stdio.h> int main(void) {
int count = 110; long sum = 10L; float average = 0.0f;
average = (float)sum/count; printf("\nAverage of the ten numbers entered is: %f\n", average); return 0;
}</source>
Average of the ten numbers entered is: 0.090909
Forced conversion
Forced conversion occurs when you are converting the value of the larger data type to the value of the smaller data type
When floating points are converted to integers, truncation occurs.
<source lang="cpp">#include <stdio.h>
main()
{
double f1 = 12.23456; printf("%d \n", (int)f1);
}</source>
12
Type casting
Type casting is used when you want to convert the value of a variable from one type to another.
Type casting does not change the actual value of the variable.
<source lang="cpp">#include <stdio.h>
main() { double d1 = 1234.56; int i1=456; printf("the value of d1 as int without cast operator %d\n",d1); printf("the value of d1 as int with cast operator %d\n",(int)d1); printf("the value of i1 as double without cast operator %f\n",i1); printf("the value of i1 as double with cast operator %f\n",(double)i1); i1 = 10; printf("effect of multiple unary operator %f\n",(double)++i1); i1 = 10; printf("effect of multiple unary operator %f\n",(double)- ++i1); i1 = 10; printf("effect of multiple unary operator %f\n",(double)- -i1); i1 = 10; printf("effect of multiple unary operator %f\n",(double)-i1++); }</source>
the value of d1 as int without cast operator 1889785610 the value of d1 as int with cast operator 1234 the value of i1 as double without cast operator 1234.559570 the value of i1 as double with cast operator 456.000000 effect of multiple unary operator 11.000000 effect of multiple unary operator -11.000000 effect of multiple unary operator 10.000000 effect of multiple unary operator -10.000000
Type conversion
- Type conversion occurs when the expression has data of mixed data types.
- In type conversion, the data type is promoted from lower to higher.
- The hierarchy of data types: double, float, long, int, short, char.
2.31.Data Type Cast 2.31.1. Type conversion 2.31.2. <A href="/Tutorial/C/0040__Data-Type/Forcedconversion.htm">Forced conversion</a> 2.31.3. <A href="/Tutorial/C/0040__Data-Type/Typecasting.htm">Type casting</a> 2.31.4. <A href="/Tutorial/C/0040__Data-Type/Datatypecastfrominttofloat.htm">Data type cast: from int to float</a>