-5

I have written the following code. Any combination of numbers less than 50000 and 60000 gives the correct answer, but for some reason I always get -1294967296 when I use 50000 and 60000. Can anyone tell me why this is?

#include <stdio.h>
int main() 
{
  int a = 50000;
  int b = 60000;
  int c = a * b;
  printf("The product of a and b is %d",c);
  return 0;
}
Ben
  • 3

1 Answers1

3

I would not say that "any" combination with numbers less than 50000 and 60000 gives you correct result.

The thing that happens here is integer overflow, as your result is 3.000.000.000, but the maximum value that a signed integer can store is 2.147.483.647.

There are two ways of fixing the problem: use unsigned integer, so the max value it can store will be a twice as much as signed int can store or use (unsigned) long long, which has way bigger max.

Edit: uint64_t, which is equivalent to unsigned long long, can store numbers from 0 to 18.446.744.073.709.551.615.

whiskeyo
  • 873
  • 1
  • 9
  • 19