You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言Integer Promotion技术疑问:两段代码的类型转换判定

整数提升(Integer Promotion)场景解答

问题1(对应第一段代码)

代码片段

//First code
#include <stdio.h>
int main() {
    double x = 11.153;
    short y = 123;
    x - y;
    return 0;
}

解答

会触发Integer Promotion:short类型变量y会先经整数提升转为int,再转换为double参与运算。

依据C标准的寻常算术转换规则:当算术运算的操作数分别为浮点类型(double)和整数类型(short)时,首先会对整数类型操作数执行整数提升——short的取值范围完全被int覆盖,因此y会被提升为int;之后再将提升后的int值转换为double,最终和x完成减法运算。

问题2(对应第二段代码)

代码片段

//Second Code
#include <stdio.h>
int main() {
    short x = 15;
    long y = 12;
    x - y;
    return 0;
}

解答

会触发Integer Promotion:short类型变量x先经整数提升转为int,再转换为long参与运算。

整数提升是寻常算术转换的前置步骤,只要操作数是short、char这类小整数类型,在参与算术运算前都会先被提升为int(若int能容纳其所有取值)。完成提升后,再根据整数转换规则,将int类型的x转换为long(因为long的类型秩高于int),最终和y执行减法运算。


内容的提问来源于stack exchange,提问作者İlker Deveci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 02:21:04