Why is -2147483648 automatically promoted to long when it can fit in int?

余生颓废 提交于 2019-12-19 10:15:58

问题


#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):

8  
4  

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

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

4  
4  

Can someone please explain what's going on?


回答1:


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

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

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

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.




回答2:


-2147483648 is the integral constant expression 2147483648 with the unary minus operator applied.

Your systems both appear to have int and long as 32-bit, and long long as 64-bit.

Since the base-10 constant 2147483648 cannot fit in long int, in C99 it has type long long int. However, C90 did not have this type, so in C90 it has type unsigned long int.

A common workaround for this issue is, as you say, to write -2147483647 - 1. You will probably see something similar as the definition of INT_MIN if you check your system's limits.h .

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).



来源:https://stackoverflow.com/questions/25658485/why-is-2147483648-automatically-promoted-to-long-when-it-can-fit-in-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!