c - 为什么最小的整数 −2147483648 的类型为 'long' ?

标签 c types

<分区>

对于一个学校项目,我必须编写 C 函数 printf。一切进展顺利,但有一个问题我找不到好的答案,所以我来了。

printf("PRINTF(d) \t: %d\n", -2147483648);

告诉我(gcc -Werror -Wextra -Wall):

   error: format specifies type 'int' but the argument has type 'long'
      [-Werror,-Wformat]
        printf("PRINTF(d) \t: %d\n", -2147483648);
                              ~~     ^~~~~~~~~~~
                              %ld

但是如果我使用一个 int 变量,一切都会很顺利:

int i;

i = -2147483648;
printf("%d", i);

为什么?

编辑:

我明白了很多点,而且很有趣。不管怎样,我猜printf正在使用 <stdarg.h>图书馆等等,va_arg(va_list ap, type)还应该返回正确的类型。对于 %d%i , 显然返回的类型是 int .它会改变什么吗?

最佳答案

在 C 中,-2147483648不是整数常量。 2147483648是整数常量,-只是应用于它的一元运算符,产生常量表达式。 2147483648 的值不适合 int (它太大了,2147483647 通常是最大的整数)因此整数常量的类型为 long ,这会导致您观察到的问题。如果您想提及 int 的下限, 要么使用宏 INT_MIN来自 <limits.h> (可移植方法)或小心避免提及 2147483648 :

printf("PRINTF(d) \t: %d\n", -1 - 2147483647);

关于c - 为什么最小的整数 −2147483648 的类型为 'long' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34724320/

相关文章:

javascript - this.type ='password' 在 IE 中不起作用,但它在所有其他浏览器中都起作用

haskell - 为什么有些运算符在赋值时会改变类型?

c - Pthread_join 崩溃程序

c - pthread_mutex_trylock 段错误

android - 堆损坏 - Android native 代码中的 SEGV_MAPERR

haskell - 为什么这个类型注释是错误的?

swift 3 : Nested Generic Type

c - libiptc : adding DNAT rule with destination IP

c - 从文件中读取数据并将其写入链表

php - php 中奇怪的 boolean 表达式求解