floating-point promotion : stroustrup vs compiler - who is right?

后端 未结 2 454
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-06 23:05

In section 10.5.1 of Stroustrup\'s new book \"The C++ Programming Language - Fourth Edition\" he says, that before an arithmetic operation is performed, integral promotion is us

2条回答
  •  清歌不尽
    2021-02-06 23:29

    I don't know what exactly Stroustrup's book says, but according to the standard, floats will not be converted to doubles in this case. Before applying most arithmetic binary operators, the usual arithmetic conversions described in 5p9 are applied:

    • If either operand is of scoped enumeration type (7.2), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.
    • If either operand is of type long double, the other shall be converted to long double.
    • Otherwise, if either operand is double, the other shall be converted to double.
    • Otherwise, if either operand is float, the other shall be converted to float.
    • Otherwise, the integral promotions (4.5) shall be performed on both operands. [...]

    The integral promotions are what causes two shorts to be converted to ints. But two floats will not be converted to doubles according to these rules. If you add a float to a double, the float will be converted to a double.

    The above is from C++11. C++03 contains the same rules, except for the one referring to scoped enumerations.

提交回复
热议问题