Complement subtraction operation

consider the following code

-sharpinclude <stdio.h>
-sharpinclude <limits.h>
int compare (const void * a, const void * b)
{
    return ( *(int*)a - *(int*)b );
}

int main(void)
{
    int a = 1;
    int b = INT_MIN;
    printf("%d %d\n", a,b);
    printf("%d\n",compare((void *)&a,(void *)&b));
    return 0;
}

output:
output is:
1-2147483648
-2147483647
I know that INT_MIN is-2147483648, and the negative number is one more than the integer, so INT_MAX is 2147483647. I searched for the subtraction of the complement on the Internet. Amurb = A + (- B), equals the complement of A plus the complement of (- B), but-B that is 2147483648 has exceeded the INT_MAX, so how is the subtraction carried out in this case?

Mar.01,2021

overflow is a characteristic of the complement, and the overflow of the intermediate process does not affect the result.

the result here overflowed because it was out of the range of positive integers (2147483649). But it is not caused by complement overflow, but the normal result within limited precision.

Let me give you an example.

2147483647 + 10 - 20

obviously the addition operation in the first step overflowed, but in the end we still get the correct 2147483637 . Because 2147483647 + 10 = 2147483657 =-2147483639 , and -2147483639-20 =-2147483659 will overflow, resulting in 2147483637 .


your question is about complement subtraction. What's the point of making a bunch of pointer conversions in the example? Use

directly
printf("%d\n", a - b);

just make the problem clear.

Integer overflow errors are ignored in

C. -INT_MIN is represented by complement or INT_MIN , where the overflow is ignored by C. So the result is 1 + INT_MIN .

Menu