#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX-1)
在阅读csapp这本书时,我发现作者提出了这个问题,但我不明白为什么要这样定义它.直接用-2147483647
来定义它有什么区别?
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX-1)
在阅读csapp这本书时,我发现作者提出了这个问题,但我不明白为什么要这样定义它.直接用-2147483647
来定义它有什么区别?
#include <stdio.h>
int main() {
printf("%d, %zu\n",-2147483647-1, sizeof(-2147483647-1));
printf("%d, %zu\n",(int)-2147483648, sizeof(-2147483648));
return 0;
}
输出:
-2147483648, 4
-2147483648, 8
该标准说:
整数常量以数字开头,但没有句点或指数部分.它可以具有指定其基址的前缀和指定其类型的后缀.
请注意,-
不是常量的一部分.它是在解释常量之后应用的求反运算符.
因此,对于-2147483648
,编译器将使用2147483648
部分来确定其类型.为此,该标准规定:
The type of an integer constant is the first of the corresponding list in which its value can be represented.
因为没有后缀指定它的类型,并且2147483648
不能由int表示(因为int_Max是2147483647
),所以它的类型将是long int
,然后sizeof INT_MIN
将是8,这是错误的.