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

后端 未结 2 630
再見小時候
再見小時候 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.

    0 讨论(0)
  • 2021-01-14 08:04

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

    0 讨论(0)
提交回复
热议问题