加法在数学上具有结合性质:
(a + b) + c = a + (b + c)
在一般情况下,此属性不适用于 float ,因为它们以有限精度表示值。
当从 C 程序生成机器代码作为优化的一部分时,编译器是否允许进行上述替换?它在 C 标准中具体说明了什么?
最佳答案
不允许编译器执行“优化”,这将导致计算出的值与根据抽象机器语义计算出的值不同。
5.1.2.3 Program execution
[#1] The semantic descriptions in this International Standard describe the behavior of an abstract machine in which issues of optimization are irrelevant.
[#3] In the abstract machine, all expressions are evaluated as specified by the semantics.
[#13] EXAMPLE 5 Rearrangement for floating-point expressions is often restricted because of limitations in precision as well as range. The implementation cannot generally apply the mathematical associative rules for addition or multiplication, nor the distributive rule, because of roundoff error, even in the absence of overflow and underflow.
在你的例子中:
(a + b) + c
甚至没有括号:
a + b + c
我们有
+
/ \
+ c
/ \
a b
并且编译器需要生成代码,就好像a
与b
相加,结果与c
相加。
关于c - C中的浮点运算是关联的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13913017/