I think I'm having an integer overflow issue and I'm not sure how to fix it. I just started C coming from Python and JS and this is all new to me.
I put a really simple example below of what is happening. I'm passing an argument from the main
function to a different function to multiply by 3, but when it's passed, the number overflows. The math works in the main
function.
#include <stdio.h>
long long calc(number) {
return number * 3;
}
int main(void)
{
long long digits = 1111111111111;
long long result = calc(digits);
printf("calc result: %lld\n", result);
long long mainTimes3 = digits * 3;
printf("main result: %lld\n", mainTimes3);
return 0;
}
I'm getting the error message
main.c:3:11: warning: type of ‘number’ defaults to ‘int’ [-Wimplicit-int]`
The printf
is showing
calc result: 438711637
main result: 3333333333333
The compiler warning hints at the problem - since you didn't explicitly define the type of the number
parameter, the compiler assumes it's an int
. Therefore number * 3
is also an int
, and an integer overflow occurs.
To solve the issue, explicitly define it as the type you intended, long long
:
long long calc(long long number){
/* Here ---^ */
return number * 3;
}