What's the correct way to use printf to print a size_t?

C++C

C++ Problem Overview


Size_t is defined as an unsigned integer, but the size of it depends on whether you're on a 32 or 64-bit machine. What's the correct and portable way to print out a size_t?

C++ Solutions


Solution 1 - C++

Try using the %zu format string

size_t val = get_the_value();
printf("%zu",val);

The z portion is a length specifier which says the argument will be size_t in length.

Source - http://en.wikipedia.org/wiki/Printf#printf_format_placeholders

Solution 2 - C++

There's a C++ tag on this, so cout << is another possible answer.

This is surprisingly hard to get right in all versions of C. In C90, casting to unsigned long should work, but that may well not work in C99, and the C99 solutions won't necessarily work in C90. The ability to reliably distinguish between C90 and C99 was introduced in the 1995 changes (specifying the allowable values for __STDC__). I don't think there is a completely portable way that works for C90, C99, and C++, although there are solutions for any individual one of those.

Solution 3 - C++

I think that the C++ answer is:

std::size_t n = 1;
std::cout << n;

For C-style IO it's a little more complicated. In C99 they added the z length modifier for size_t values. However, previous to TR1 this is not supported so you are left with casting to a specific size like:

std::size_t n = 1;
std::printf("%lu\n", static_cast<unsigned long>(n));

Then again, unsigned long long isn't really supported by C++ anyway so the above will work fine since unsigned long is the largest legal integral type. After TR1 you can use %zu safely for size_t values.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbradtgmurrayView Question on Stackoverflow
Solution 1 - C++JaredParView Answer on Stackoverflow
Solution 2 - C++David ThornleyView Answer on Stackoverflow
Solution 3 - C++D.ShawleyView Answer on Stackoverflow