user379888
user379888

Reputation:

Overflow with product of ints

In the code below, the value of prod is not 9,000,000; it gets a garbage value. Why do we need num1 and num2 to be of type long?

#include <stdio.h>
int main()
{
    int num1 = 3000, num2 = 3000;
    long int prod = num1 * num2;
    printf("%ld\n", prod);
    return 0;
}

Upvotes: 2

Views: 203

Answers (1)

whooops
whooops

Reputation: 935

When num1*num2 is computed, it is stored in an intermediate variable that is of the same type (i.e., an int), which comes up as garbage because it's not big enough. Then, the intermediate variable is stored in a long int, but the computed answer was already turned into garbage.

The solution is to cast one of the arguments of the multiplication.

long int prod = (long int)num1 * num2;

This way, the intermediate computation will use the bigger of the two types, and store it temporarily as a long int.

Upvotes: 9

Related Questions