3

I read that conversion from int to long long int is promotion and hence thought that there shouldn't be any issue as there is no loss of data, unlike the vice versa conversion.

But when I multiply two ints of large value and store it in long long int, it is showing me negative number.

Eg:

int a=1000000, b=1000000;
long long int c=a*b;
cout<<c;

The above code gives me a negative value. Can someone explain why?

Rama
  • 3,222
  • 2
  • 11
  • 26
Bharg
  • 311
  • 1
  • 2
  • 15
  • 1
    This is because you use ints to make an operation which results in a return value which is also an int that might overflow and then you have the promotion which is already too late. – Adrian Lis Feb 22 '17 at 16:21
  • I tried the same with C where I used the "%lld" placeholder in printf for printing. Even then, it is showing me negative value. – Bharg Feb 22 '17 at 16:21
  • 2
    possibly a duplicate http://stackoverflow.com/questions/31662792/multiplication-of-two-integers-in-c – Ap31 Feb 22 '17 at 16:25

3 Answers3

8

a*b is still of type int. Once it's evaluated, the result is then converted to long long int. At that point it's too late to avoid overflow. Convert one of your values to long long int before preforming the multiplication. Try this :

#include <iostream>

int main()
{
    int a = 1000000, b = 1000000;
    long long int c = static_cast<long long int>(a)*b;
    std::cout << c;
    return 0;
};
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
5

The multiplication is happening as an int, which overflows, giving Undefined Behaviour (in this case overflow, which is very normal - your combination of compiler+settings may even guarantee it), and after that the result is being converted to long long.

I think you want to do the conversion on one of the arguments before multiplication, so that the multiplication is performed using long longs:

long long c = static_cast<long long>(a)*b;

In this way, b will be promoted to long long before the multiplication takes place, and the whole operation will be performed safely, and with the desired result.

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
1

Because multiplying two ints will result in another int that comes with all the overflow problems attached. This int is then (after the fact) promoted to a long long int which still means it's not what you want.

Promote at least one of the operands to have the other promoted and get the result you want.

nvoigt
  • 75,013
  • 26
  • 93
  • 142