0

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?

3
  • Why would there be a difference? - A will need to be converted in either case. Commented Jun 2, 2022 at 10:43
  • You'll have such problem with division, but not with addition nor the other operations. Also consider the type the result is casted to is important: int C = A + B will indeed incude lose of precision.
    – user8849929
    Commented Jun 2, 2022 at 10:50
  • Use double instead of float.
    – i486
    Commented Jun 2, 2022 at 10:59

2 Answers 2

5

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:

  1. 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.

3

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.