Why do I get -1 when I print the following?
unsigned long long int largestIntegerInC = 18446744073709551615LL;
printf ("largestIntegerInC = %d\n", largestIntegerInC);
I know I should use llu instead of d, but why do I get -1 instead of 18446744073709551615LL?
Is it because of overflow?
In C (99),
LLONG_MAX, the maximum value oflong long inttype is guaranteed to be at least9223372036854775807. The maximum value of anunsigned long long intis guaranteed to be at least18446744073709551615, which is 264−1 (0xffffffffffffffff).So, initialization should be:
(Note the
ULL.) SincelargestIntegerInCis of typeunsigned long long int, you should print it with the right format specifier, which is"%llu":The second
printf()above is wrong, it can print anything. You are using"%d", which meansprintf()is expecting anint, but gets aunsigned long long int, which is (most likely) not the same size asint. The reason you are getting-1as your output is due to (bad) luck, and the fact that on your machine, numbers are represented using two’s complement representation.To see how this can be bad, let’s run the following program:
On my Macbook, running the program with
"%d %d %d"gives me-1 -1 42, and on a Linux machine, the same program with the same format gives me-1 42 -1. Oops.In fact, if you are trying to store the largest
unsigned long long intnumber in yourlargestIntegerInCvariable, you should includelimits.hand useULLONG_MAX. Or you should store assing-1to your variable:In the above program, both
largestIntegerInCandnextcontain the largest possible value forunsigned long long inttype.