INT_MIN表达的问题


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

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 来表示。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容