今天在《深入理解计算机系统》的书中看到:
define INT_MIN (-2147483647 - 1)
为什么要这样定义,直接写成-2147483648不好吗?
解释:
- 可以参看这篇博文,或者这篇微话题。
- 首先得知道常量表达式和整数的区别:
根据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 来表示。
网友评论