nitin_cherian
nitin_cherian

Reputation: 6655

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 ?

Upvotes: 1

Views: 217

Answers (1)

Mitch Wheat
Mitch Wheat

Reputation: 300559

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;

Upvotes: 2

Related Questions