Does one double promote every int in the equation to double?

后端 未结 4 1970
粉色の甜心
粉色の甜心 2020-12-06 09:13

Does the presence of one floating-point data type (e.g. double) ensure that all +, -, *, /, %, etc math operations assume double operands?

If the story

4条回答
  •  感动是毒
    2020-12-06 10:01

    I purposefully did not compile and run then on my system, since this is the type of thing that could be compiler dependent.

    This is not compiler dependent. C++ clearly defines the order of these operations and how they are converted.

    How the conversion happens is dependent on the order of operations.

    double result1 = a + b / d + c; // equal to 4 or to 4.5?
    

    In this example, the division happens first. Because this is an int divided by a double, the compiler handles this by converting the int into a double. Thus, the result of b / d is a double.

    The next thing that C++ does is add a to the result of b / d. This is an int added to a double, so it converts the int to a double and adds, resulting in a double. The same thing happens with c.

    double result3 = a / b + d; // equal to 4 or to 4.5?
    

    In this example, division is handled first. a and b are both ints, so no conversion is done. The result of a / b is of type int and is 0.

    Then, the result of this is added to d. This is an int plus a double, so C++ converts the int to a double, and the result is a double.

    Even though a double is present in this expression, a / b is evaluated first, and the double means nothing until execution reaches the double. Therefore, integer division occurs.

    I find promotion and conversion rules pretty complex. Usually integer-like numbers (short, int, long) are promoted to floating-point equivalents (float, double). But things are complicated by size differences and sign.

    See this question for specifics about conversion.

提交回复
热议问题