c – How can one print a size_t variable portably using the printf family?
c – How can one print a size_t variable portably using the printf family?
Use the z
modifier:
size_t x = ...;
ssize_t y = ...;
printf(%zun, x); // prints as unsigned decimal
printf(%zxn, x); // prints as hex
printf(%zdn, y); // prints as signed decimal
Looks like it varies depending on what compiler youre using (blech):
- gnu says
%zu
(or%zx
, or%zd
but that displays it as though it were signed, etc.) - Microsoft says
%Iu
(or%Ix
, or%Id
but again thats signed, etc.) — but as of cl v19 (in Visual Studio 2015), Microsoft supports%zu
(see this reply to this comment)
…and of course, if youre using C++, you can use cout
instead as suggested by AraK.
c – How can one print a size_t variable portably using the printf family?
For C89, use %lu
and cast the value to unsigned long
:
size_t foo;
...
printf(foo = %lun, (unsigned long) foo);
For C99 and later, use %zu
:
size_t foo;
...
printf(foo = %zun, foo);