I have a variable of type size_t
, and I want to print it using printf()
. What format specifier do I use to print it portably?
In 32-bit machine, %u
seems right. I compiled with g++ -g -W -Wall -Werror -ansi -pedantic, and there was no warning. But when I compile that code in 64-bit machine, it produces warning.
size_t x = <something>;
printf( "size = %u\n", x );
warning: format '%u' expects type 'unsigned int',
but argument 2 has type 'long unsigned int'
The warning goes away, as expected, if I change that to %lu
.
The question is, how can I write the code, so that it compiles warning free on both 32- and 64- bit machines?
Edit: I guess one answer might be to "cast" the variable into an unsigned long
, and print using %lu
. That would work in both cases. I am looking if there is any other idea.
For C89, use
%lu
and cast the value tounsigned long
:For C99 and later, use
%zu
:Extending on Adam Rosenfield's answer for Windows.
I tested this code with on both VS2013 Update 4 and VS2015 preview:
VS2015 generated binary outputs:
while the one generated by VS2013 says:
Note:
ssize_t
is a POSIX extension andSSIZE_T
is similar thing in Windows Data Types, hence I added<BaseTsd.h>
reference.Additionally, except for the follow C99/C11 headers, all C99 headers are available in VS2015 preview:
Also, C11's
<uchar.h>
is now included in latest preview.For more details, see this old and the new list for standard conformance.
On some platforms and for some types there are specific printf conversion specifiers available, but sometimes one has to resort to casting to larger types.
I've documented this tricky issue here, with example code: http://www.pixelbeat.org/programming/gcc/int_types/ and update it periodically with info on new platforms and types.
if you want to print the value of a size_t as a string you can do this:
result is:
number: 2337200120702199116
text: Lets go fishing in stead of sitting on our but !!
Edit: rereading the question because of the down votes i noted his problem is not %llu or %I64d but the size_t type on different machines see this question https://stackoverflow.com/a/918909/1755797
http://www.cplusplus.com/reference/cstdio/printf/
size_t is unsigned int on a 32bit machine and unsigned long long int on 64bit
but %ll always expects a unsigned long long int.
size_t varies in length on different operating systems while %llu is the same
Looks like it varies depending on what compiler you're using (blech):
%zu
(or%zx
, or%zd
but that displays it as though it were signed, etc.)%Iu
(or%Ix
, or%Id
but again that's signed, etc.) — but as of cl v19 (in Visual Studio 2015), Microsoft supports%zu
(see this reply to this comment)...and of course, if you're using C++, you can use
cout
instead as suggested by AraK.