【问题标题】:What happens if I add an unsigned int to a negative int and the arithmetic result is positive?如果我将 unsigned int 添加到负 int 并且算术结果为正会发生什么?
【发布时间】:2017-12-05 07:26:04
【问题描述】:

当我要执行以下代码时,我认为有符号的 int i 会被转换为无符号的,结果会是一个很大的正数,但结果是 2

int main()
{
    unsigned u = 10; int i = -8;
    std::cout << u + i << std::endl; 
    return 0;
}

【问题讨论】:

标签: c++ type-conversion expression language-lawyer


【解决方案1】:

在执行加法时,对操作数执行通常的算术转换,其中状态为 ([expr]/11.5.3):

  • 否则,如果具有无符号整数类型的操作数的秩大于或等于另一个操作数类型的秩, 带符号整数类型的操作数应转换为 无符号整数类型的操作数。

所以-8 被转换为无符号数。其中根据[conv.integral]/2如下:

如果目标类型是无符号的,则结果值是最小的 与源整数一致的无符号整数(模 2n 其中 n 是用于表示无符号类型的位数)。

这会将我们的号码转换为(MAX_UINT + 1) - 8。现在,由于无符号加法是模块化的 2n ([basic.fundamental]/4):

无符号整数应遵守算术模 2n 的定律,其中 n 是该特定整数大小的值表示中的位数。

结果必须是(MAX_UINT + 1) - 8 + 10MAX_UINT + 1,也就是2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 2017-05-07
    • 2011-11-01
    • 2013-05-19
    • 2011-02-17
    • 1970-01-01
    • 2018-11-12
    相关资源
    最近更新 更多