I am using the below code to get a long int sum of 2 numbers.
I take the inputs as long ints and expecting a long int answer through printf but am getting the result as a negative number.
#include <stdio.h>
int main(void)
{
long x;
long y;
printf("enter x:\n");
scanf("%ld", &x);
printf("enter y:\n");
scanf("%ld", &y);
printf("%li\n", x + y);
}
>Solution :
If I make one small change to your code, I get your output:
#include <stdio.h>
#include <stdint.h>
int main(void)
{
int32_t x;
int32_t y;
printf("enter x:\n");
scanf("%d", &x);
printf("enter y:\n");
scanf("%d", &y);
printf("%i\n", x + y);
}
% ./a.out
enter x:
2000000000
enter y:
2000000000
-294967296
This indicates that you’re using a platform where long is 32-bits. To ensure you’re using a 64-bit signed int, use int64_t rather than long.
You should also get in the habit of checking the return value from scanf so that you can know when I/O has failed and address it immediately.