首页 > 刷 csapp 碰到的一道的练习题.

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

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

#include<stdio.h>

int tadd_ok(int x, int y){
  int sum = x + y;
  return (sum - x == y) && (sum - y == x);
}

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

/*
  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.

 */

难道不是永远返回非0值


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

【热门文章】
【热门文章】