Search code examples
c++c++11visual-c++standards

Does dividing float by int always give float? C++


I been programming on C and C++ for some time, and was always sure that double dividing int gives double, or double dividing int also give double (only int by int gives int) and same with adding. I was doing my assignment and was sure that 1 + (f*f + 10) / k, where f is double and k is int would always return double. I was using g++ -std=gnu++11 command on mac (so it's clang compiler probably) and I got tests passed (I indeed got float number as a result), but my teacher says that it not for sure that it will be float (he is using windows). Is that behavior platform specific? Is there any C++ standard that describes double on int division? Thank you! My code:

#include <iostream>
using namespace std;

int main() {
    int  N;
    double f, P = 0;
    cin >> N >> f;
    for (double k = 1; k <= N; k++){
      P += 1 + (f*f + 10) / k;
    }
    cout << P;
    return 0;
}

Solution

  • From the C++20 standard draft [expr.arith.conv]:

    Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

    • (1.1) If either operand is of scoped enumeration type, no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.
    • (1.2) If either operand is of type long double, the other shall be converted to long double.
    • (1.3) Otherwise, if either operand is double, the other shall be converted to double.
    • (1.4) Otherwise, if either operand is float, the other shall be converted to float.
    • (1.5) Otherwise, the integral promotions ([conv.prom]) shall be performed on both operands.56 Then the following rules shall be applied to the promoted operands: ...

    This paragraph has not changed in any fundmental way since at least C++11 (which was the oldest I checked), so your teacher has some explaining to do.