Search code examples
c++c++11floating-pointtype-conversioninteger-overflow

When does C++11 do arithmetic type conversions relative to operator precedence?


If I have the following code:

double compute(double val1,
               int32_t val2,
               int32_t val3,
               int32_t val4) {
  return val1 + val2 * val3 * val4;
}

How does the C++11 language specify that the multiplication be performed? E.g., are val1, val2, and val3 multiplied as 32 bit integers, according to operator precedence, possibly overflowing, and then converted to a double, or are they multiplied as doubles?

In general, what exactly does the standard say on this subject? Has it changed in subsequent versions of C++ (e.g., C++17)?


Solution

  • The expression

    val1 + val2 * val3 * val4
    

    has the type of double, but the multiplication part is of type int32_t. If we apply the rules on how it is evaluated we have

    val1 + (val2 * val3 * val4)
    

    because multiplication has a higher precedence, it will be evaluated without considering the type of val1 and since all of the operands have the same type the result type will be the same as the operands. That result is then converted to a double and added to val1. This behavior has not changed in any of the versions of C++.

    To get the multiplication to happen as double you need to cast either val2 or val3 to a double, which will make the entire multiplication part evaluated as a double. That would look like

    val1 + (static_cast<double>(val2) * val3 * val4)
    

    the parentheses are not needed but I like using them to show the grouping