Is floating point addition commutative in C++?

后端 未结 3 885
梦如初夏
梦如初夏 2020-12-01 13:41

For floating point values, is it guaranteed that a + b == b + a ?

I believe this is guaranteed in IEEE754, however the C++ standard does not specify tha

3条回答
  •  误落风尘
    2020-12-01 14:31

    No, the C++ language generally wouldn't make such a requirement of the hardware. Only the associativity of operators is defined.

    All kinds of crazy things do happen in floating-point arithmetic. Perhaps, on some machine, adding zero to an denormal number produces zero. Conceivable that a machine could avoid updating memory in the case of adding a zero-valued register to a denormal in memory. Possible that a really dumb compiler would always put the LHS in memory and the RHS in a register.

    Note, though, that a machine with non-commutative addition would need to specifically define how expressions map to instructions, if you're going to have any control over which operation you get. Does the left-hand side go into the first machine operand or the second?

    Such an ABI specification, mentioning the construction of expressions and instructions in the same breath, would be quite pathological.

提交回复
热议问题