For example,
If I have int A = 106
and float B = 10.345f
, which operation has better precision, A + B
or (float)A + B
? Or do they actually have the same precision?
No there is no difference. When adding two arithmetic types, there is a set of implicit conversions that are applied by the compiler. You can find a list of these rules for example on cppreference. In your case rule number 3) applies:
- Otherwise, if one operand is float, float complex, or float imaginary, the other operand is implicitly converted as follows:
- integer type to float (the only real type possible is float, which remains as-is)
- [...]
So if you do not explicitely state the conversion using a cast, the compiler implicitely does exactly the same conversion for you. And because the expressions are actually the same, there is also no difference in precision.
If you look at the compiler results https://godbolt.org/z/x5174j8n9, then you see that functions
float add1(int A, float B)
{
return A + B;
}
float add2(int A, float B)
{
return (float)A + B;
}
give identical compiler output with O2
or O3
optimization enabled:
add1(int, float):
movaps xmm1, xmm0
pxor xmm0, xmm0
cvtsi2ss xmm0, edi
addss xmm0, xmm1
ret
add2(int, float):
movaps xmm1, xmm0
pxor xmm0, xmm0
cvtsi2ss xmm0, edi
addss xmm0, xmm1
ret
A
will need to be converted in either case.int C = A + B
will indeed incude lose of precision.double
instead offloat
.