Two pad overflows in C

I saw in C an error code that was used to check if the result adds overflow or not. It works fine with char, but gives the wrong answer when the arguments are int, and I could not understand why.
Here is the code with the arguments short.

short add_ok( short x, short y ){
    short sum = x+y;
    return (sum-x==y) && (sum-y==x);
}

This version works fine, the problem occurs when changing the arguments to int(you can check it with INT_MAX)
You see what is wrong here?

+5
source share
4 answers

2s ( ). y, y , ( undefined).

+5

, int short. - x+y x y, int, short .

: return x+y<=SHRT_MAX && x+y>=SHRT_MIN;

+5

C , char ( ), . , , . , ?

, , , , . ? .

char , , - 127, - -128. , : "char = 128", , , i, -128. , , , "char = 129", -127. ? , , (). , "char = -129", 127, "char = -130", 126, .

( ) 127, 126, 125,..., -126, -127, -128 ( )

, , , .

wrap-around point for char type


: , int char short, ( , int, short char, ), "short" char , int, int, :

return (sum-x==y) && (sum-y==x);

, , , int, , . , INT_MAX+1, INT_MIN, INT_MIN-1 == INT_MAX, TRUE! , "short" char int, (). , int , , .

char , . , , , , . , C, char "short" int, , int, , .


, MinGW Ubuntu 12.04, , . , , short , int, int. :

return (sum-x==y) && (sum-y==x);

, "sum-x" "y" (int), , ( ):

short sum = x+y;

. 32767 2 , , :

short sum = x+y;

-32767, - . , :

return (sum-x==y) && (sum-y==x);

"sum-x" (-32767 - 32767) y (2) ( ), -, - , "sum-x" -65534, y, .

, :

#include <stdio.h>

short add_ok( short x, short y ){
    short sum = x+y;
    return (sum-x==y) && (sum-y==x);
}

int main(void) {

    short i, ii;
    scanf("%hd %hd", &i, &ii);
    getchar();

    printf("%hd", add_ok(i, ii));

    return 0;
}

.

, , , , , , - .

: C99 6.3.1.3 , GNU C .

+3

, , 1, .

return (y==y) && (x==x);

:

return 1

, - undefined behavior - , , x + y-y == x y + x-x == y.

If it was an unsigned operation, it would fail, since the overflow is simply performed as a modulo operation, it is quite simple to prove that

x+y mod SHRT_MAX - y mod SHRT_MAX == x

and similarly for the opposite case.

+1
source

All Articles