美文网首页
INT_MIN表达的问题

INT_MIN表达的问题

作者: Nibnat | 来源:发表于2015-01-21 10:21 被阅读37次

今天在《深入理解计算机系统》的书中看到:

define INT_MIN (-2147483647 - 1)

为什么要这样定义,直接写成-2147483648不好吗?


解释:

  1. 可以参看这篇博文,或者这篇微话题
  2. 首先得知道常量表达式和整数的区别:
    根据C Reference Manual定义常量表达式:

Constant expressions
In several places C requires expressions which evaluate to a constant: after case, as array bounds, and in initializers.
In the first two cases, the expression can involve only integer constants, character constants, and sizeof
expressions, possibly connected by the binary operators
+ − * /%& | ˆ << >>
or by the unary operators
− ˜ Parentheses can be used for grouping, but not for function calls.
A bit more latitude is permitted for initializers; besides constant expressions as discussed above, one can also apply
the unary & operator to external scalars, and to external arrays subscripted with a constant expression. The unary
& can also be applied implicitly by appearance of unsubscripted external arrays. The rule here is that initializers
must evaluate either to a constant or to the address of an external identifier plus or minus a constant.

根据GNU C Manual定义的整数:

An integer constant is a sequence of digits, with an optional prefix to denote a number base.

所以,2147483648是整数,-2147483648是常量表达式,对于后者,我们是对整数取负。32位可以容纳整型-2147483648 --- 2147483647,所以如果对整数取负会造成溢出,损坏了值。所以我们用-2147483647 - 1 来表示。

相关文章

  • INT_MIN表达的问题

    今天在《深入理解计算机系统》的书中看到: define INT_MIN (-2147483647 - 1)...

  • 运算相关:除法

    除法: abs()是对int取绝对值,当整数为INT_MIN时,取绝对值还是INT_MIN;使用labs()先将数...

  • 924. Minimize Malware Spread

    方法一:并查集 方法二:BFS 问题:?奇怪,如果直接temp.size()>maxv,输出为INT_MIN,想不明白

  • INT_MIN

    表示为整型的下限INT_MAX 表示为上限 对字符串s.length() 可以求出字符串的长度对数组numnum....

  • LeetCode124. 二叉树中的最大路径和

    主要代码: int ans = INT_MIN; int oneSideMax(TreeNode* root) {...

  • 8. String to Integer (atoi)字符串转整

    整型限定在INT_MIN: -2147483648和INT_MAX: 2147483647之间,若出现溢出的情况,...

  • c++ 关键点

    INT_MIN、INT_MAX mid = l + (r -l) / 2 (r -l) /2 向下取整 1/2 =...

  • leetcode 7

    反转32 signed int INT_MIN INT_MAX 定义在 中INT_MAX 0x7fffffff该解...

  • Validate Binary Search Tree

    解題思路 : test case 很賊會使用 INT_MAX 或是 INT_MIN 來測試 所以在 soluti...

  • C/C++中int上下限

    1. 整形上下限 在C/C++中整形的上下限使用常量INT_MAX和INT_MIN表示。 2. 整形上下限的大小 ...

网友评论

      本文标题:INT_MIN表达的问题

      本文链接:https://www.haomeiwen.com/subject/izshxttx.html