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

c c++


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?

10/12/2017 1:13:59 PM

Accepted Answer

Try using the %zu format string

size_t val = get_the_value();

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

10/12/2017 1:14:13 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow