gpt4 book ai didi

c++ - 如果我将一个 unsigned int 添加到一个负 int 并且算术结果为正,会发生什么情况?

转载 作者:搜寻专家 更新时间:2023-10-31 00:27:48 36 4
gpt4 key购买 nike

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

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

最佳答案

执行加法时,对操作数执行通常的算术转换,即 ( [expr]/11.5.3 ):

  • Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.

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

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type).

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

Unsigned integers shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.

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

关于c++ - 如果我将一个 unsigned int 添加到一个负 int 并且算术结果为正,会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47648216/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com