Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

large negative number multiplied by -1 gives output negative c++

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.

like image 360
kamleshi9 Avatar asked Dec 02 '13 17:12

kamleshi9


People also ask

What happens if you multiply negative by negative?

Correct answer: Multiplying a negative number and another negative number makes the product positive.

When negative number is multiplied to a negative number the product is negative number?

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.

Why is a negative number multiplied by a negative number a 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.


2 Answers

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.

like image 87
jman Avatar answered Nov 20 '22 04:11

jman


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.

like image 40
Dweeberly Avatar answered Nov 20 '22 05:11

Dweeberly