Why long long and int multiplication produces overflow?

Viewed 88

I am testing this piece of code in c

  long long n = 1000000;
  long long var1,var2;
  int x = 50000;
  var1 = n * x * x;
  var2 = x * x * n;
  printf("var1 = %lld\n", var1);
  printf("var2 = %lld\n", var2);

When i run it produces this output

var1 = 2500000000000000
var2 = -1794967296000000

I don't understand why changing the order of variables being multiplied produced an overflow.

1 Answers

In this case associativity is left to right, so what happens is:

  var1 = (n * x) * x;
  var2 = (x * x) * n;

In case of n * x, the x will be converted to long long since n is long long, so it has a higher conversion rank. Therefore, this partial result will not overflow.

But with x * x, both operands are int therefore the result will be int as well, and that can't hold the value 2,500,000,000, which causes the overflow.

Related