I am currently learning C and typecasts and it is suggesting that if I want to convert an int to a float I should precede the variable with (float)
to do this.
However, when I don't use the typecast, the answer still comes out correct, even though I am mixing the ints and floats.
Can someone explain why/when I would need to use the typecast (float)
in particular?
#include <stdio.h>
int main(void) {
int A, B, E;
float C, D;
A = 2;
B = 1;
C = 12.5;
D = C * A + B;
E = C * A + B;
printf("Total is %.1f\n", D);
printf("total is %d", E);
return 0;
}
You never need to explicitly typecast to float
unless you want to force a precise operation between to int
s, for example
int a = 10;
int b = 3;
a / b
yields 3
of type int
(because it's an integer division), while a / (float)b
yields 3.3333..
of type float
.
C language specification in addition ensures you that an integer type can be implicitly converted to a float whenever it's necessary to do so (eg. an operation with another float). In addition narrowing can occur if you assign a float
value to an int
variable, in that case value is truncated. (§6.3.1.4 of C11)