混合符号整数数学取决于可变大小 [英] mixed-sign integer math depends on variable size
问题描述
函数 g1()
和 g2()
具有相同的逻辑,但输入类型有不同的大小。为什么它们对负和的返回不同的结果?
Functions g1()
and g2()
have identical logic, but the input types have different sizes. Why do they return different results for negative sums?
/*BINFMTCXX: -Wall -Werror -Wextra -std=c++11
*/
#include <stdio.h>
#include <stdint.h>
char g1( int32_t a, uint32_t b ) { return a+b<9; } // fails when a+b is negative
char g2( int16_t a, uint16_t b ) { return a+b<9; } // works if no overflow
int main()
{
for ( int a=-2, b=0; a<=2; a++ )
{
fprintf(stderr,"a=%+d, b=%d, g1=%+d, g2=%+d %s\n", a, b, g1(a,b), g2(a,b), g1(a,b)==g2(a,b)?"":"!" );
}
return 0;
}
当我运行它时,它显示 g1 )在
a + b
为负数时失败:
$ ./mixed_sign_math_per_size.cpp
a=-2, b=0, g1=+0, g2=+1 !
a=-1, b=0, g1=+0, g2=+1 !
a=+0, b=0, g1=+1, g2=+1
a=+1, b=0, g1=+1, g2=+1
a=+2, b=0, g1=+1, g2=+1
结果与C C ++。
推荐答案
由于通常的算术转换, a
和 b
code> g2 的主体被提升为 int
,这就是为什么这个函数工作得很好。
As a result of the usual arithmetic conversions, both a
and b
in g2
's body are promoted to int
, which is why that function works perfectly well.
对于 g1
,因为( u
) int32_t
没有小于 int
的等级,不进行升级,最后一个项目符号(11.5.5 )适用。两个操作数都转换为无符号类型,在 a
的情况下会导致下溢,产生大于9的值。因此 g1
返回 1
( true
)。
For g1
, because (u
)int32_t
does not have a rank less than that of int
, no promotion occurs, and the very last bullet point (11.5.5) applies. Both operands are converted to the unsigned type, which - in a
's case - causes an underflow, producing a value much greater than 9. Hence g1
returned 1
(true
).
这篇关于混合符号整数数学取决于可变大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!