# 用 C 代码确定减法溢出

##### 问题描述投票：0回答：1
``````#include <stdio.h>

int tsub_ok(int x, int y);

int tsub_ok(int x,int y)
{
int dif = 0; //The difference of our two numbers.
dif = x - y; //X is the minuhend. Y is the subtrahend.
printf("DIFFERENCE: %d\n", dif); //Output difference.

if ((x >= 0 && y < 0) || (x < 0 && y >= 0)) { //IF THE SIGNS ARE DIFFERENT (they have to be)
if (x >= 0 && y < 0 && dif < 0) { //MINUHEND IS POSITIVE, SUBTRAHEND IS NEGATIVE, AND DIFFERENCE IS NEGATIVE. (OVERFLOW OCCURS)
printf("OVERFLOW\n");
return 0;
}
else if (x < 0 && y >= 0 && dif >= 0) { // MINUHEND IS NEGATIVE, SUBTRAHEND IS POSITIVE, DIFFERENCE IS POSITIVE. (OVERFLOW OCCURS)
printf("OVERFLOW\n");
return 0;
}
else {
printf("No Overflow!!\n"); //Overflow does NOT occur in any other condition.
return 1;
}
}
else { //IN ANY OTHER CONDITION, THERE IS NO OVERFLOW.
printf("No Overflow!!\n");
return 1;
}
}

int main() {
int x, y;

scanf("%d %d", &x, &y);
int ans = tsub_ok(x, y);
printf("%d\n", ans);

return 0;
}
``````

c overflow
##### 1个回答
0

``dif = x - y;``
，可能会溢出，导致未定义的行为（UB）并使其余代码变得毫无意义。

``````#include <limits.h>

int is_undefined_sub1(int a, int b) {
return (b < 0) ? (a > INT_MAX + b) : (a < INT_MIN + b);
}
``````