问题描述
有关学校的项目,我已经到code中的C函数的printf。事情会pretty不错,但有一个问题,我无法找到一个很好的答案,所以我在这里。
For a school project, I've to code the C function printf. Things are going pretty well, but there is one question I can't find a good answer to, so here I am.
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变量,一切都很顺利:
But if I use an int variable, everything is going well:
int i;
i = -2147483648;
printf("%d", i);
为什么?
我明白了很多分,是非常有趣的。总之,我想的printf
使用< STDARG.H>
librairy等,在va_arg(va_list的AP,类型)
也应该返回正确的类型。对于%d个
和%I
,显然返回的类型是 INT
。它是否在改变什么?
I understood many points and were very interesting. Anyway, I guess printf
is using the <stdarg.h>
librairy and so, va_arg(va_list ap, type)
should also return the right type. For %d
and %i
, obviously the type returned is an int
. Does it change anything ?
推荐答案
在C, -2147483648
不是一个整型常量。 2147483648
是一个整型常量,而 -
只是一个一元运算符适用于它,产生一个恒定的前pression。值 2147483648
不适合在 INT
(它的One过大, 2147483647
通常的最大整数),因此整型常量的类型长
,这将导致你观察到的问题。如果你想提的下限值的 INT
,可以使用宏 INT_MIN
从 &LT;&limits.h中GT;
(便携式办法)或谨慎避免提及 2147483648
:
In C, -2147483648
is not an integer constant. 2147483648
is an integer constant, and -
is just a unary operator applied to it, yielding a constant expression. The value of 2147483648
does not fit in an int
(it's one too large, 2147483647
is typically the largest integer) and thus the integer constant has type long
, which causes the problem you observe. If you want to mention the lower limit for an int
, either use the macro INT_MIN
from <limits.h>
(the portable approach) or carefully avoid mentioning 2147483648
:
printf("PRINTF(d) \t: %d\n", -1 - 2147483647);
这篇关于为什么最小的INT,-2147483648,有型“长”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!