Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between %zu and %lu in C

What is the difference between %zu and %lu in string formatting in C? %lu is used for unsigned long values and %zu is used for size_t values, but in practice, size_t is just an unsigned long. CppCheck complains about it, but both work for both types in my experience.

Is %zu just a standardized way of formatting size_t because size_t is commonly used, or is there more to it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

but in practice, size_t is just an unsigned long

Not necessarily. There are systems with a 32 bit long and a 64 bit size_t. MSVC is one of them.

Given the following:

printf("long: %zu\n", sizeof(long));
printf("long long: %zu\n", sizeof(long long));
printf("size_t: %zu\n", sizeof(size_t));

Compiling under MSVC 2015 in x86 mode outputs:

long: 4
long long: 8
size_t: 4

While compiling in x64 mode outputs:

long: 4
long long: 8
size_t: 8

Having a separate size modifier for size_t ensures you’re using the correct size.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading