[英]Why is -2147483648 automatically promoted to long when it can fit in int?
#include <stdio.h>
int main()
{
printf("%zu\n", sizeof(-2147483648));
printf("%zu\n", sizeof(-2147483647-1));
return 0;
}
The above code gives as output (gcc): 上面的代码给出了输出(gcc):
8
4
Why is -2147483648
automatically promoted to long
in 1 st printf
even when it can fit in an int
? 为什么
-2147483648
在第一个 printf
自动提升为long
,即使它可以适合int
?
Also, I tried the same in MinGW and it gives the output: 此外,我在MinGW中尝试了同样的方法,它给出了输出:
4
4
Can someone please explain what's going on? 有人可以解释一下发生了什么吗?
The number 2147483648 is too large to fit into an int
, so it is promoted to long
. 数字2147483648太大而无法放入
int
,所以它被提升为long
。
Then, after the number has already been promoted to long
, its negative is computed, yielding -2147483648. 然后,在数字已经提升为
long
,计算其负数,产生-2147483648。
If you're curious, you can look at limits.h
. 如果你很好奇,你可以看看
limits.h
。 On my platform, which uses glibc, 在我的平台上,使用glibc,
# define INT_MIN (-INT_MAX - 1)
# define INT_MAX 2147483647
On MinGW, sizeof(long) == 4
, so promotion to long
won't cut it. 在MinGW上,
sizeof(long) == 4
,所以升级到long
不会削减它。 According to the C11 standard, the value must be promoted to long long
. 根据C11标准,该值必须提升为
long long
。 This doesn't happen, probably because your MinGW compiler is defaulting to C90 or earlier. 这不会发生,可能是因为您的MinGW编译器默认为C90或更早版本。
-2147483648
is the integral constant expression 2147483648
with the unary minus operator applied. -2147483648
是应用了一元减运算符的积分常量表达式2147483648
。
Your systems both appear to have int
and long
as 32-bit, and long long
as 64-bit. 您的系统似乎都有
int
和long
为32位, long long
为64位。
Since the base-10 constant 2147483648
cannot fit in long int
, in C99 it has type long long int
. 由于base-10常量
2147483648
不能适合long int
,因此在C99中它具有long long int
类型。 However, C90 did not have this type, so in C90 it has type unsigned long int
. 但是,C90没有这种类型,所以在C90中它有
unsigned long int
类型。
A common workaround for this issue is, as you say, to write -2147483647 - 1
. 正如您所说,此问题的常见解决方法是编写
-2147483647 - 1
。 You will probably see something similar as the definition of INT_MIN
if you check your system's limits.h
. 如果检查系统的
limits.h
您可能会看到类似于INT_MIN
定义的INT_MIN
。
Regarding the output 4
, this suggests that on your MinGW system you are using C90 and on your other system you are using C99 or C11 (or C++, or GCC extensions). 关于输出
4
,这表明在您的MinGW系统上使用的是C90,而在您的其他系统上,您使用的是C99或C11(或C ++或GCC扩展)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.