Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct printf format specifier for size_t: %zu or %Iu?

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

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)?

like image 317
Patrick Avatar asked Mar 25 '13 07:03

Patrick


People also ask

What is the format specifier for Size_t?

The correct way to print size_t variables is use of “%zu”. In “%zu” format, z is a length modifier and u stand for unsigned type.

What is the meaning of %U in printf () statement?

An unsigned Integer means the variable can hold only a positive value. This format specifier is used within the printf() function for printing the unsigned integer variables. Syntax: printf(“%u”, variable_name);

For what is the format specifier %u used?

%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.

Why %U is used in C?

The %u format specifier is implemented for fetching values from the address of a variable having an unsigned decimal integer stored in the memory. It is used within the printf() function for printing the unsigned integer variable.


2 Answers

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).

like image 34
Alexey Frunze Avatar answered Sep 24 '22 13:09

Alexey Frunze


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()); 
like image 58
Pavel P Avatar answered Sep 21 '22 13:09

Pavel P