Why is the output of this program -2147483648?
#include <iostream>
using namespace std;
int main() {
long long a=-2147483648;
a=a*-1;
cout<<a;
return 0;
}
It should be 2147483648 because it is in range of long long
. Why the sign is not changing? I have even tried abs()
function but the result is the same.
Also more surprising is that this program outputs 2147483648:
#include <iostream>
using namespace std;
int main() {
long long a=-2147483648;
a=a*-1;
a=a*-1;
cout<<a;
return 0;
}
The second time, multiplying by -1 worked. If it matters, I'm using C++ 4.8.1.
Correct answer: Multiplying a negative number and another negative number makes the product positive.
There are two simple rules to remember: When you multiply a negative number by a positive number then the product is always negative. When you multiply two negative numbers or two positive numbers then the product is always positive.
The fact that the product of two negatives is a positive is therefore related to the fact that the inverse of the inverse of a positive number is that positive number back again.
Enable -Wall
and you'll see the answer.
foo.C:5: warning: this decimal constant is unsigned only in ISO C90
Use -2147483648LL
in place of your constant.
Add 'll' to the end of your declaration:
long long a=-2147483648ll;
I checked this on IDEONE and saw the problem and verified the fix. The problem is that your constant value exceeds that for a default int so you have to type it (as long long) to get the constant you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With