今天在《深入理解計(jì)算機(jī)系統(tǒng)》的書(shū)中看到:
define INT_MIN (-2147483647 - 1)
為什么要這樣定義庶弃,直接寫(xiě)成-2147483648不好嗎?
解釋?zhuān)?/strong>
- 可以參看這篇博文,或者這篇微話題蝴乔。
- 首先得知道常量表達(dá)式和整數(shù)的區(qū)別:
根據(jù)C Reference Manual定義常量表達(dá)式:
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.
根據(jù)GNU C Manual定義的整數(shù):
An integer constant is a sequence of digits, with an optional prefix to denote a number base.
所以,2147483648是整數(shù)驮樊,-2147483648是常量表達(dá)式淘这,對(duì)于后者剥扣,我們是對(duì)整數(shù)取負(fù)。32位可以容納整型-2147483648 --- 2147483647铝穷,所以如果對(duì)整數(shù)取負(fù)會(huì)造成溢出钠怯,損壞了值。所以我們用-2147483647 - 1 來(lái)表示曙聂。