抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

带符号整型变量

加法

1
2
3
4
5
6
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 + 1
  2. 正溢出:2147483647 + 1
  3. 负溢出:–2147483648 + (–1)

减法

1
2
3
4
5
6
7
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 – 1
  2. 正溢出:2147483648 – (–1)
  3. 负溢出: –2147483648 – 1

乘法

1
2
3
4
5
6
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;
}
  1. 未溢出:2 * 2
  2. 正溢出:2147483647 * 2
  3. 负溢出:2147483647 * (–2)

无符号整型变量

加法

1
2
3
4
int uadd_ok(unsigned x,unsigned y) {
unsigned sum = x + y;
return sum >= x;
}
  1. 未溢出:1 + 2
  2. 溢出:1 + 4294967295

减法

1
2
3
4
int usub_ok(unsigned x,unsigned y) {
unsigned sum = x - y;
return sum <= x;
}
  1. 未溢出:2 – 1
  2. 溢出:1 – 2

乘法

1
2
3
4
int umultiply_ok(unsigned x,unsigned y) {
unsigned sum = x * y;
return sum >= x || sum == 0;
}
  1. 未溢出:2 * 2
  2. 溢出:4294967295 * 2

评论