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);
}
If I make one small change to your code, I get your output:
This indicates that you're using a platform where
longis 32-bits. To ensure you're using a 64-bit signed int, useint64_trather thanlong.We can use the
PRIi64macro from theinttypes.hheader to make sure we get the right format specifier.You should also get in the habit of checking the return value from
scanfso that you can know when I/O has failed and address it immediately.