gpt4 book ai didi

c - C : Whats the rationale behind this particular rule 中的常用算术转换

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:35 25 4
gpt4 key购买 nike

来自 k&R C

  • First, if either operand is long double, the other is converted to long double.
  • Otherwise, if either operand is double, the other is converted to double.
  • Otherwise, if either operand is float, the other is converted to float.
  • Otherwise, the integral promotions are performed on both operands; ...

这意味着下面的表达式

char a,b,c;

c=a+b;

实际计算为

c = char((int)a+(int)b);

这条规则背后的基本原理是什么?

如果 a、b 和 c 很短,这些转换会发生吗?

最佳答案

不,事实并非如此。 C99 部分 5.1.2.3 程序执行,第 10 条涵盖完全您询问的情况:

EXAMPLE 2
In executing the fragment
char c1, c2;
c1 = c1 + c2;
the "integer promotions" require that the abstract machine promote the value of each variable to int size and then add the two ints and truncate the sum.

Provided the addition of two chars can be done without overflow, or with overflow wrapping silently to produce the correct result, the actual execution need only produce the same result, possibly omitting the promotions.

因此,如果已知操作会产生相同的结果,则不需要使用更宽的值。

但是如果您想要了解标准中特定决定背后的基本原理,您必须查看,..... 等待,..... 是的,Rationale document :-)

在该基本原理的第 6.3.1.8 节(部分与标准中的部分匹配)中,它指出:

Explicit license was added to perform calculations in a “wider” type than absolutely necessary, since this can sometimes produce smaller and faster code, not to mention the correct answer more often.

Calculations can also be performed in a “narrower” type by the as if rule so long as the same end result is obtained.

关于c - C : Whats the rationale behind this particular rule 中的常用算术转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8937676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com