Correct printf format specifier for size_t: %zu or %Iu?
C++CVisual Studio-2010PrintfFormat SpecifiersC++ Problem Overview
I want to print out the value of a size_t
variable using printf
in C++ using Microsoft Visual Studio 2010 (I want to use printf
instead of <<
in this specific piece of code, so please no answers telling me I should use <<
instead).
According to the post
> https://stackoverflow.com/questions/2125845/platform-independent-size-t-format-specifiers-in-c
the correct platform-independent way is to use %zu
, but this does not seem to work in Visual Studio. The Visual Studio documentation at
> http://msdn.microsoft.com/en-us/library/vstudio/tcxf1dw6.aspx
tells me that I must use %Iu
(using uppercase i
, not lowercase l
).
Is Microsoft not following the standards here? Or has the standard been changed since C99? Or is the standard different between C and C++ (which would seem very strange to me)?
C++ Solutions
Solution 1 - C++
MS Visual Studio didn't support %zu
printf specifier before VS2013
. Starting from VS2013 (e.g. _MSC_VER
>= 1800
) %zu
is available.
As an alternative, for previous versions of Visual Studio if you are printing small values (like number of elements from std containers) you can simply cast to an int
and use %d
:
printf("count: %d\n", (int)str.size()); // less digital ink spent
// or:
printf("count: %u\n", (unsigned)str.size());
Solution 2 - C++
Microsoft's C compiler does not catch up with the latest C standards. It's basically a C89 compiler with some cherry-picked features from C99 (e.g. long long
). So, there should be no surprise that something isn't supported (%zu
appeared in C99).
Solution 3 - C++
The Microsoft documentation states:
> The hh
, j
, z
, and t
length prefixes are not supported.
And therefore %zu
is not supported.
It also states that the correct prefix to use for size_t
is I
– so you'd use %Iu
.
Solution 4 - C++
Based on the answer from here, %z
is a C99 addition. Since MSVC doesn't support any of the later C standards, it's no surprise that %z
isn't supported.