2

我正在使用 GCC v4.4.5,并且我发现了一个我没想到的默认整数提升方案。

为了激活足够的警告以防止隐式错误,我激活了选项 -Wconversion,从那时起,我注意到当我执行下面的代码时,出现警告“从 'int' 转换为 'short int' 可能会改变其值”

signed short sA, sB=1, sC=2;
sA = sB + sC;

这意味着"sB + sC"被提升为int,然后分配给sA,它是有符号的 short。要修复这个警告,我必须像这样投射它。

signed short sA, sB=1, sC=2;
sA = ( signed short )( sB + sC );

此警告也出现在下面的代码中。

signed short sA=2;
sA += 5;

并且可以通过删除运算符+=来修复...

sA = ( signed short )( sA + 1 );

这有点烦人,因为我不能使用运算符+=-=

我希望 GCC 根据操作数选择正确的整数提升。我的意思是,sA=sB+sCsA+=5不应该被提升为int因为它们都被签署了 short

我知道默认情况下提升为int可以防止溢出错误,但这有点烦人,因为我必须转换大部分代码或将变量更改为int

我可以使用 GCC 选项来展示这个整数提升方案吗?

谢谢你的帮助。

4

1 回答 1

2

这不是 gcc,这是标准 C 语义。

Per 6.3.1.1:2, an object or expression with an integer type whose integer conversion rank is less than or equal to the rank of int and unsigned int is converted to int or unsigned int depending on the signedness of the type, prior to participating in arithmetic expressions.

The reason C behaves this way is to allow for platforms where ALU operations on sub-int types are less efficient than those on full int types. You should perform all your arithmetic on int values, and convert back to short only for storage.

于 2012-06-25T10:15:38.620 回答