刷 csapp 碰到的一道的练习题.

书中要求写一个带有两个整形参数的函数,要求判断是否会发生溢出,书中给出了一段错误代码,问我为什么这么判断是错误的,我只能举出反例,却说不上为什么.代码如下:

#include<stdio.h>

int tadd_ok(int x, int y){
  int sum = x + y;
  return (sum - x == y) && (sum - y == x);
}
阅读 5.1k
4 个回答

难道不是永远返回非0值

我自己尝试着解释了一下, 不知道正不正确

/*
  The aim of this function is to judge if the addition of two number
  will result overflow. If not return 1 else 0.
 */
int tadd_ok(int x, int y){
  int sum = x + y;
  return (sum - x == y) && (sum - y == x);
}

/*
  The is the reason why this is wrong : 
there are two situations that will cause overflow.
 assume the int is w-bit-long.

  1. two negtive number and get a positive number.
  In this case : x + y < -2^(w-1)   => since the minium number of int is -2^(w-1)
  so in fact sum =  (x + y + 2^w)  => for example -1 + -8 will get 7 if w = 4.
  so when you use sum - x you will get (y + 2^w) % 2^w result y
  (when the value is bigger than 2^w) it's the same for sum -  y.

  2. two positive number and get a negtive number.
  In this case : x + y > 2^(w-1) - 1 => since the maximum number of int is 2^(w-1) - 1
  so sum = (x + y - 2^w => for example 5 + 5 will get -6 if w = 4
  so when you use sum - x you will get (y - 2^w) since y < 2^(w-1) - 1 so the value will be
  smaller than -1 - 2(w-1) which is also over flow so in fact it is (y - 2^w) % 2^w == y.

 */

上述代码不能用来检测有符号数溢出,补码加会形成一个阿贝尔群,因此表达式(x+y)-x求值得到 y,无论加法是否溢出,而 (x+y)-y 总是会求值得到 x
证明过程:
http://hi.csdn.net/attachment...

整形加法本来就有可能溢出啊

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进