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

后端 未结 2 654
再見小時候
再見小時候 2021-01-14 07:35
#include 

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

2条回答
  •  情歌与酒
    2021-01-14 07:45

    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.

提交回复
热议问题