简体   繁体   English

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

[英]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.

相关问题 原始数据(字节)和有符号/无符号变量 - Raw data (bytes) and signed/unsigned variables 无符号变量的算术运算产生有符号值,是标准行为吗? - Arithmetic operations on unsigned variables produce signed values, is it standard behavior? 使用enable_if为有符号和无符号变量创建一个可变构造函数 - make a variadic constructor for signed and unsigned variables using enable_if 对C ++中的标志使用signed和unsigned变量 - Usage of signed vs unsigned variables for flags in C++ 有符号和无符号整数在实现方面的差异C ++ - Difference in implementation of signed and unsigned integers C++ 存储指向静态变量的指针 - Storing pointers to static variables istringstream不在变量中存储任何内容 - istringstream not storing anything in variables static_cast 之间有区别吗<unsigned> (有符号) vs std::bit_cast<unsigned> (签)? - Is there difference between static_cast<unsigned>(signed) vs std::bit_cast<unsigned>(signed)? 非本机长度的有符号和无符号整数的性能差异 - Performance difference of signed and unsigned integers of non-native length 未初始化变量的后果:int vs unsigned char - Consequences of uninitialised variables: int vs unsigned char
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM