为什么-2147483648自动提升到可以适合int的长度? [英] Why is -2147483648 automatically promoted to long when it can fit in int?

查看:141
本文介绍了为什么-2147483648自动提升到可以适合int的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

int main()
{
    printf("%zu\n", sizeof(-2147483648));
    printf("%zu\n", sizeof(-2147483647-1));
    return 0;
}

上面的代码给出了输出(gcc):

The above code gives as output (gcc):

8  
4  

为何<1c $ c> -2147483648 在1 st <$ c中自动提升为 long $ c> printf 即使它适合于 int

Why is -2147483648 automatically promoted to long in 1st printf even when it can fit in an int?

另外,我在MinGW中也做了同样的处理,并输出结果:

Also, I tried the same in MinGW and it gives the output:

4  
4  

有人可以解释发生了什么吗?

Can someone please explain what's going on?

推荐答案

数字2147483648太大而无法放入 int 中,因此被升级至

The number 2147483648 is too large to fit into an int, so it is promoted to long.

然后,数字已被提升为 long ,计算其负数,产生-2147483648。

Then, after the number has already been promoted to long, its negative is computed, yielding -2147483648.

如果您好奇,可以看看 limits.h 。在我使用glibc的平台上,

If you're curious, you can look at limits.h. On my platform, which uses glibc,

#  define INT_MIN       (-INT_MAX - 1)
#  define INT_MAX       2147483647

在MinGW上, sizeof(long)== 4 ,所以升级到 long 不会削减它。根据C11标准,该值必须被提升为 long long 。这不会发生,可能是因为您的MinGW编译器默认为C90或更早版本。

On MinGW, sizeof(long) == 4, so promotion to long won't cut it. According to the C11 standard, the value must be promoted to long long. This doesn't happen, probably because your MinGW compiler is defaulting to C90 or earlier.

这篇关于为什么-2147483648自动提升到可以适合int的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆