C程序中的整数推广

Rav*_*avi 5 c integer-promotion

我写了一个简单的C程序,想知道整数提升是否正在发生.

请解释整数推广如何发生以及如何避免?

/* start of main */

unsigned short int res;
unsigned short int bsp;
signed short int analog;

bsp = 2215;
analog = 2213;
if((signed short int)(bsp - analog) > 0){
    res = bsp - analog;
    printf("%d", res);
}
else{
    res = analog - bsp;
    printf("%d", res);
}
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 2

我将把这个答案限制为int32 位和short16 位。

然后bsp - analog是类型的表达式int。

short如果bsp - analog不能在 a 中表示,则将其转换为 a 的行为是未定义的short。所以写代码要(signed short int)(bsp - analog)小心。

您的通话中隐含了res对 an的提升。intprintf

最后,避免不必要的晋升的最佳方法是始终与同一类型的人合作。考虑在您的情况下使用 anint或 a 。long