C语言中的常规算术转换:此特定规则背后的原理是什么 [英] Usual arithmetic conversions in C : Whats the rationale behind this particular rule

查看:84
本文介绍了C语言中的常规算术转换:此特定规则背后的原理是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自k& R C

From k&R C

  • 首先,如果其中一个操作数为long double,则另一个操作数将转换为long double.
  • 否则,如果其中一个操作数为double,则另一个将转换为double.
  • 否则,如果其中一个操作数为float,则另一个将转换为float.
  • 否则,对两个操作数执行积分提升; ...
  • 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);

此规则背后的原理是什么?

What is the rationale behind this rule?

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

Do these conversions happen if a, b and c were short ?

推荐答案

不,这不是真的. C99第5.1.2.3 Program execution节第10条涵盖了完全您所询问的情况:

No that's not actually true. C99 Section 5.1.2.3 Program execution, clause 10 covers exactly the case you ask about:

示例2
在执行片段
char c1, c2;
c1 = c1 + c2;
整数提升"要求抽象机将每个变量的值提升为int大小,然后将两个int相加并截断总和.

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.

因此,如果已知该操作会产生相同的结果,则无需使用更宽的值.

So, if the operation is known to produce the same result, there's no requirement for using the wider values.

但是,如果您想了解标准中做出特定决定的依据,则必须看一下.....等待它,...是的,

But if you want the rationale behind a specific decision made in the standard, you have to look at, ..... wait for it, ..... yes, the Rationale document :-)

该理由的第6.3.1.8节(各部分与标准中的内容相符)指出:

In section 6.3.1.8 of that rationale (sections match those in the standard), it states:

添加了显式许可证,以绝对必要的更广泛"类型执行计算,因为这有时可以生成更小,更快的代码,更不用说正确答案了.

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语言中的常规算术转换:此特定规则背后的原理是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆