[英]Storing difference of unsigned variables into signed variables
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 ? 如果在程序的后面使用带符号的变量,是否有任何潜在的问题?
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.