posts - 403, comments - 310, trackbacks - 0, articles - 7
            BlogJava :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          A Note on TMin

          Posted on 2007-09-19 21:26 ZelluX 閱讀(545) 評論(1)  編輯  收藏 所屬分類: C/C++
          關(guān)于表示32位整型中最小的數(shù)-2147483648的一篇文章,from CSAPP http://csapp.cs.cmu.edu/public/tmin.html

          Summary

          Due to one of the rules for processing integer constants in ANSI C, the numeric constant -2147483648 is handled in a peculiar way on a 32-bit, two's complement machine.

          The problem can be corrected by writing -2147483647-1, rather than -2147483648 in any C code.


          Description of Problem

          The ANSI C standard requires that an integer constant too large to be represented as a signed integer be ``promoted'' to an unsigned value. When GCC encounters the value 2147483648, it gives a warning message: ``warning: decimal constant is so large that it is unsigned.'' The result is the same as if the value had been written 2147483648U.
          ANSI C標準中要求太大的整型常量都表示為unsigned

          The compiler processes an expression of the form -X by first reading the expression X and then negating it. Thus, when the C compiler encounters the constant -2147483648, it first processes 2147483648, yielding 2147483648U, and then negates it. The unsigned negation of this value is also 2147483648U. The bit pattern is correct, but the type is wrong!

          書上的一個小錯誤

          Writing TMin in Code

          The ANSI C standard states that the maximum and minimum integers should be declared as constants INT_MAX and INT_MIN in the file limits.h. Looking at this file on an IA32 Linux machine (in the directory /usr/include), we find the following declarations:
          /* Minimum and maximum values a `signed int' can hold.  */
          #define INT_MAX 2147483647
          #define INT_MIN (-INT_MAX - 1)

          This method of declaring INT_MIN avoids accidental promotion and also avoids any warning messages by the C compiler about integer overflow.

          The following are ways to write TMin_32 for a 32-bit machine that give the correct value and type, and don't cause any error messages:

          • -2147483647-1
          • (int) 2147483648U
          • 1<<31
          The first method is preferred, since it indicates that the result will be a negative number.
          表示-2147483648的幾種方法

          評論

          # re: A Note on TMin  回復(fù)  更多評論   

          2007-09-28 16:31 by 千里冰封
          又是英文啊
          主站蜘蛛池模板: 辽宁省| 喀喇沁旗| 文安县| 峡江县| 平定县| 大竹县| 金塔县| 阿坝| 靖远县| 兴化市| 和林格尔县| 南召县| 仙桃市| 安福县| 武强县| 吴川市| 南通市| 买车| 资中县| 彰化市| 彭泽县| 隆子县| 青河县| 丰城市| 新龙县| 天镇县| 法库县| 星子县| 分宜县| 淄博市| 五指山市| 攀枝花市| 马边| 略阳县| 台中市| 鹤庆县| 新龙县| 修水县| 克什克腾旗| 大足县| 德州市|