开发者

Cannot assign the value of INT_MIN to a long long

signed long long value = -2147483648;
    cout << ((signed long long)valu开发者_开发百科e);

outputs 2147483648 (no minus sign), why?


signed long long value = -2147483648;

2147483648 cannot be represented in a 32-bit signed integer, so it is converted to an unsigned, then unary minus is applied (which doesn't change anything), and then it is assigned to the signed long long. Use -2147483648LL


A literal integer, in C++, has the type int. If it doesn't fit into that type, it may be interpreted as an unsigned integer. However, it is not guaranteed that it automatically will be treated as a larger integer type.

The standard, fortunately, support a suffix notation to specify the explicit type of the literal.

In this case, you should use -2147483648LL.


Your original code may contain undefined behavior, but it looks more like a compiler bug to me. As others have pointed out, the constant 2147483648 cannot be represented in a 32 bit int. According to the standard, "The type of an integer literal depends on its form, value, and suffix. If it is decimal and has no suffix, it has the first of these types in which its value can be represented: int, long int; if the value cannot be represented as a long int, the behavior is undefined." The draft C++0x adds long long at the end of these.

If LONG_MAX is greater than 2147483648, then the type of the literal is long, and the minus should give the correct value. Otherwise, if the compiler already supports long long (and since you're declaring a variable of this type, one must assume that it does), the type of 2147483648 is long long, and the minus should give the correct value. If the compiler doesn't support long long, and long is only 32 bits, then your code has undefined behavior, so anything the compiler does is "correct".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜