Addition of different types of variables: unsigned int + int

1. Case phenomenon: The
addition structure of different types of values ​​is inconsistent with the ideal value.

int main()
{
    
    
    int i = -20;
    unsigned int j = 10;
    cout << i + j << endl;
    system("pause");
    return 0;
}
输出结果:4 294 967 286

2^32-10=4 294 967 296-10=4 294 967 286

2. Reason:
Add two compatible values ​​of different types, and which number can represent a larger number (positive number) is converted to that number type. For example, short+ long, must be converted to long; unsigned+ signed, must be converted to unsigned.
2.1, the case explained
in the 32-bit machine unsigned intlargest representable 2^32 - 1; intlargest representable 2^31-1;
so inton into the unsigned int, due i<0, i.e., ithe most significant bit is a sign bit, into unsigned intthe most significant bit is the sign bit longer, but a number of effective positive Bit, so the sum of the two will be a big positive number.
Detailed calculation process

1、int -20在32位计算机中的存储形式为:1111 1111 1111 1111 1111 1111 1110 1100 第一位1为符号位,表示负数
2、unsigned 10在32位计算机中的存储形式为:0000 0000 0000 0000 0000 0000 0000 1010
3、unsigned+int 后结果转为unsigned存储,故int -20转化为unsigned int,由于符号位为1,转为unsigned int 后最高位不再是符号位,而是一个最高正的位数,两者相加为1111 1111 1111 1111 1111 1111 1111 0110 即为4 294 967 286。

3. Why "Which one can represent a larger number is converted to which type"?
becauseThe computer (note that it is a computer, not a compiler, or an operating system) always hopes to include the results as large as possible to prevent overflows from causing errors (although some people will say what to do with underflows, don’t forget to add and subtract negative numbers Complementary code also becomes the addition operation of positive numbers)

to sum up:

1. Add two compatible values ​​of different types, and which number can represent a larger number (positive number) is converted to that number type. For example, short+ long, must be converted to long; unsigned+ signed, must be converted to unsigned.

Reference materials:
1. This article is reprinted and rearranged. The original link: [This article explains the principle] The problem of adding unsigned and int
2. [This article talks about the phenomenon] Talking about the problem of adding unsigned int and int

Guess you like

Origin blog.csdn.net/qq_33726635/article/details/108568474