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?
>Solution :
but in practice,
size_tis just anunsigned 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.