unsigned long long vs unsigned long(portability point of view)

erin c picture erin c · May 17, 2012 · Viewed 15.4k times · Source

I want to be able to use large positive integers(8 bytes) in my project, even though sizeof(unsigned long) yields 8 in my system, I read that in most systems unsigned long is only 4 bytes and I decided to give unsigned long long a go, since it's guaranteed to be at least 8 bytes.

The more I use it though, I saw that it is not super portable as well, for instance in some systems(depending on the compiler) printf formats it with %llu, in some it formats it with %lld.

My code will only run in 64 bit debian machines, in which unsigned long will be 8 bytes. Portability is not a big issue. Is it an overkill to use unsigned long long over unsigned long under these circumstances, are there any other benefits of using unsigned long long over unsigned long?

Answer

James Kanze picture James Kanze · May 17, 2012

unsigned long long is guaranteed to be at least 64 bits, regardless of the platform. (There are platforms where it is more—I know of 72 bits and 96 bits—but they are rare, and decidedly exotic.) unsigned long is guaranteed to be at least 32 bits. If you need more than 32 bits, I would recommend unsigned long long.

With regards to the formatting, with printf, you should use "%llu" (since it is unsigned); "%lld" is for signed long long.