Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing long int value in C

Tags:

c

I have two variables of long int type as shown below:

long int a=-2147483648, b=-2147483648; a=a+b;  printf("%d",a); 

I am getting zero. I tried changing the type to long long int, but I'm still not getting the correct answer.

like image 631
ranger101 Avatar asked Jul 22 '13 03:07

ranger101


People also ask

How do I print long long int in printf?

Printing short, long, long long, and unsigned Types To print an unsigned int number, use the %u notation. To print a long value, use the %ld format specifier. You can use the l prefix for x and o, too. So you would use %lx to print a long integer in hexadecimal format and %lo to print in octal format.

Can we use %d for long?

You should scanf for a %ld if that is what you are expecting. But since a long is larger than your typical int , there is no issue with this.

Is long int valid in C?

For instance, the long int, short int, unsigned int, signed int, etc., are all very valid data types in the C programming language.


1 Answers

You must use %ld to print a long int, and %lld to print a long long int.

Note that only long long int is guaranteed to be large enough to store the result of that calculation (or, indeed, the input values you're using).

You will also need to ensure that you use your compiler in a C99-compatible mode (for example, using the -std=gnu99 option to gcc). This is because the long long int type was not introduced until C99; and although many compilers implement long long int in C90 mode as an extension, the constant 2147483648 may have a type of unsigned int or unsigned long in C90. If this is the case in your implementation, then the value of -2147483648 will also have unsigned type and will therefore be positive, and the overall result will be not what you expect.

like image 100
caf Avatar answered Oct 06 '22 01:10

caf