简体   繁体   中英

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

you could easily verify with a test case:

a = unsigned Int max;
b = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM