将无符号变量的差异存储到有符号变量中

时间:2022-02-24 11:37:03

Is there any potential problem in storing the difference of two unsigned integer variables into a signed integer variable ?

将两个无符号整数变量的差异存储到有符号整数变量中是否存在任何潜在问题?

Consider the example below:

考虑以下示例:

#include <stdio.h>

int main()
{
    unsigned int a, b, d1;
    signed int d2;

    a = 20;
    b = 200;

    d1 = a - b; 
    d2 = a - b; // Line 1

    printf("d1 = %u\n", d1);
    printf("d2 = %d\n", d2);

    return 0;

}

If the signed variable is used later in the program, is there any potential problem ?

如果稍后在程序中使用了signed变量,是否存在任何潜在问题?

1 个解决方案

#1


2  

Yes, you could overflow.

是的,你可能会溢出。

The difference of 2 unsigned integers can be as large as an unsigned integer and that won't fit in a signed integer (of the same type) [ unless you were to wrap around to negative, but pretty sure you don't want that].

2个无符号整数的差异可能与无符号整数一样大,并且不适合有符号整数(相同类型)[除非你要回转为负数,但很确定你不希望这样] 。

you could easily verify with a test case:

您可以轻松验证测试用例:

a = unsigned Int max;
b = 0;

#1


2  

Yes, you could overflow.

是的,你可能会溢出。

The difference of 2 unsigned integers can be as large as an unsigned integer and that won't fit in a signed integer (of the same type) [ unless you were to wrap around to negative, but pretty sure you don't want that].

2个无符号整数的差异可能与无符号整数一样大,并且不适合有符号整数(相同类型)[除非你要回转为负数,但很确定你不希望这样] 。

you could easily verify with a test case:

您可以轻松验证测试用例:

a = unsigned Int max;
b = 0;