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

后端 未结 2 453
佛祖请我去吃肉
佛祖请我去吃肉 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:18

    In the meantime Stroustrup seems to recognised the refer sentence is not correct or at least misleading. He has removed the sentence, about the floating-point promotion, from section 10.5.1.

    Please see errata of 3rd printing of 4th edition on Stroustrup's web page:

    pg 267: s/Similarly, floating-point promotion is used to create doubles out of floats//

    (Remark: The expression s/regexp/replacement/ is similar to sed unix tool semantics. It searches for the pattern regexp and replaces it with replacement. Nothing in our case.)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题