Why it is different between -2147483648 and (int)-2147483648

前端 未结 4 410
Happy的楠姐
Happy的楠姐 2020-12-03 18:42

When I run the following code under Windows7 x64, compiled with GCC of MinGW, the result seems to be underflowed:

cout<<-2147483648 ;    //Output: 2147         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-03 19:13

    First of all, it is important to understand that there are no negative integer literals.

    Others have explained why the OP's particular compiler behaves as it does. But for the record, this is what the compiler should do, between the lines, on a 32-bit system:

    • You have the number 2147483648, which cannot fit in a 32-bit signed int of two's complement format.
    • Since it is a decimal number (without an U, L or similar suffix), the compiler checks its internal type table (1) for such an integer constant. It works like this: try to fit it in an int, if it doesn't fit, try a long, if it doesn't fit there either, try a long long, if it doesn't fit there either, we have undefined behavior. A C or C++ compiler following the latest standard will not attempt to fit it in unsigned types.
    • In this specific case, the number doesn't fit in an int nor in a long, so the compiler decides to use a long long as type for the literal.
    • You then use the unary minus operator on this literal, ending up with the number -2147483648. Ironically this would fit in a signed int of two's complement format, but it is too late to change the type, the compiler has already picked long long as the type.

    (1) This "internal table" looks different if you have an unsigned suffix, or if you have hex format etc. If there is an unsigned suffix, it will only check if the number fits in unsigned numbers. If there is hex notation (but no suffix), it will check int, then unsigned int, then long and so on.

提交回复
热议问题