signed long long value = -2147483648;
cout << ((signed long long)value);
outputs 2147483648 (no minus sign), why?
signed long long value = -2147483648;
cout << ((signed long long)value);
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
g++
. Isn't that covered in the standard? –
Package int
s are 64 bit on my machine. Sorry. –
Package long long
is), then you could use -(long long)2147483648
. But it would be rather strange for a C++ compiler to support long long
as an extension but not also support LL
. –
Damiendamietta unsigned int
, but in the standard, behaviour is undefined if the value cannot be represented as long
(2.13.1/2). The standard never makes decimal integer literals with no suffix unsigned. –
Damiendamietta 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
.
long int
, but that might well be no larger than int
. –
Damiendamietta LL
until C++0x. –
Prud 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".
© 2022 - 2024 — McMap. All rights reserved.
long long
is not a "built-in-type" until C++0x. – Prud