问题出自于CSAPP:p_105的Web Aside DATA:TMIN
#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX - 1)
文中提出了“为什么INT_MIN 没有直接宏定义为-2147483648 ?"的疑问,但是没有解答。
查了下,发现教材中又有一处错了。
关于整型常量的定义:
“An integer constant begins with a digit, but has no period or exponent part. It may have a prefix that specifies its base and a suffix that specifies its type.”
定义中没有提到符号,因此:25是整型常量,-25是整型常量表达式;
-2147483648是由一个一元减号运算符和一个整型常量2147483648构成的整型常量表达式。
一个没有后缀的整型常量按下面顺序进行匹配
C89 : int, long int, unsigned long int
C99 : int, long int, long long int
C++ : int, long int, long long int
对于C89,由于2147483648不能为int或long int所标示,因此就变成了unsigned long int型,即使加上一元减号运算符还是unsigned long int型,根本就就没有32位机下有符号的整型变量最小值。
所以将INT_MIN宏定义为(-2147483647-1)
#include <stdio.h>
int main(void)
{
if(-2147483648 > 0)
printf("positive\n");
if(-2147483647 - 1 < 0)
printf("negative\n");
return 0;
}gcc -std=c89 执行结果为positive negative (c89 将2147483648当成 unsinged long int)gcc -std=c99 执行结果为negative (c99将2147483648当成long long int)
原文链接: https://www.cnblogs.com/openix/p/3186417.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/95567
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!