Reputation: 480
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;
}
Upvotes: 2
Views: 3478
Reputation: 133577
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)
Upvotes: 2
Reputation: 521194
By convention, C will upcast an arithmetic expression into a float
if the expression has even one float
variable. So the following two expressions would end up being float
:
int A = 3;
float F = 1.0;
float result1 = A * F; // result is 3.0
float result2 = A / F; // result is also 3.0
float result3 = A - F; // result is 2.0
In your actual code, you have the following expression:
D = C * A + B;
In terms of order of operations, we can rewrite the right hand side like this:
((C * A) + B);
C will evaluate this as follows:
((float + int) + int)
((float) + int)
float
Upvotes: 1