11

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?

3
  • 3
    Except that size_t could be unsigned long long and then %lu would be wrong but %zu is still correct. Commented Jul 29, 2022 at 13:09
  • 7
    "in practice, size_t is just an unsigned long". No, in 32-bit MS VC size_t is 32-bits, in 64-bit it is 64 bits. But long is 32 bits in both. Commented Jul 29, 2022 at 13:10
  • 1
    An unsigned long is at least 32-bit. size_t is at least 16-bit. Commented Jul 29, 2022 at 13:37

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

3 Comments

From what I understand, the size of size_t is implementation and machine dependent, and using %zu makes formatting easier and independent of anything. Am I correct?
@Brogolem35 Yes, the z modifier is specifically for size_t, so it will be correct for whatever the size of size_t happens to be.
In practice, size_t is usually the same size as a pointer (but there are likely to be some exceptions - EDIT e.g. AS/400 has 128-bit pointers and 32-bit size_t!).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.