Long not giving the result I expect it to

60 Views Asked by At

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);
}
1

There are 1 best solutions below

3
Chris On BEST ANSWER

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.

We can use the PRIi64 macro from the inttypes.h header to make sure we get the right format specifier.

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main(void)
{
    int64_t x;
    int64_t y;      
    printf("enter x:\n");
    scanf("%" PRIi64, &x);
    printf("enter y:\n");
    scanf("%" PRIi64, &y);
    printf("%" PRIi64 "\n", x + y);
}

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.