带符号整型变量
加法
c
int tadd_ok(int x,int y) {
int sum = x + y;
int neg_over = x < 0 && y < 0 && sum >= 0;
int pos_over = x >= 0 && y >= 0 && sum < 0;
return !neg_over && !pos_over;
}
- 未溢出:1 + 1
- 正溢出:2147483647 + 1
- 负溢出:–2147483648 + (–1)
减法
c
int tsub_ok(int x,int y) {
y = - y;
int sum = x + y;
int neg_over = x < 0 && y < 0 && sum >= 0;
int pos_over = x >= 0 && y >= 0 && sum < 0;
return !neg_over && !pos_over;
}
- 未溢出:1 – 1
- 正溢出:2147483648 – (–1)
- 负溢出: –2147483648 – 1
乘法
c
int tmultiply_ok(int x,int y) {
int multiply = x * y;
int neg_over = ((x < 0 && y > 0) || (x > 0 && y < 0)) && multiply >= 0;
int pos_over = ((x >= 0 && y >= 0) || (x < 0 && y < 0)) && multiply < 0;
return !neg_over && !pos_over;
}
- 未溢出:2 * 2
- 正溢出:2147483647 * 2
- 负溢出:2147483647 * (–2)
无符号整型变量
加法
c
int uadd_ok(unsigned x,unsigned y) {
unsigned sum = x + y;
return sum >= x;
}
- 未溢出:1 + 2
- 溢出:1 + 4294967295
减法
c
int usub_ok(unsigned x,unsigned y) {
unsigned sum = x - y;
return sum <= x;
}
- 未溢出:2 – 1
- 溢出:1 – 2
乘法
c
int umultiply_ok(unsigned x,unsigned y) {
unsigned sum = x * y;
return sum >= x || sum == 0;
}
- 未溢出:2 * 2
- 溢出:4294967295 * 2