隐式类型转换的意外结果

时间:2019-06-10 22:48:20

标签: c implicit-conversion

我正在尝试在我编写的某些代码中在intunsigned int之间进行隐式类型转换。编译器给出了意外结果。

根据有符号和无符号整数(相等秩)之间隐式转换的规则,代码应产生一个较大的正数作为其输出。

unsigned int q = 90;
int w = -1;
printf("q+w=%u\n", q + w);

作为该程序的输出,您可以查看here,结果是89。我希望在进行算术运算之前,int w会被强制转换为类型unsigned int。 ,并产生预期的结果。

1 个答案:

答案 0 :(得分:1)

-1被转换为UINT_MAX(转换为无符号的正式规则是您repeatedly add or subtract the maximum+1 until the result fits (6.3.1.3p2))。 UINT_MAX+90 == 89

相关问题