I want to print out a variable of type size_t
in C but it appears that size_t
is aliased to different variable types on different architectures. For example, on one machine (64-bit) the following code does not throw any warnings:
size_t size = 1;
printf("the size is %ld", size);
but on my other machine (32-bit) the above code produces the following warning message:
warning: format '%ld' expects type 'long int *', but argument 3 has type 'size_t *'
I suspect this is due to the difference in pointer size, so that on my 64-bit machine size_t
is aliased to a long int
("%ld"
), whereas on my 32-bit machine size_t
is aliased to another type.
Is there a format specifier specifically for size_t
?
MSDN, says that Visual Studio supports the "I" prefix for code portable on 32 and 64 bit platforms.
Yes, there is. It is
%zu
(as specified in ANSI C99).Note that
size_t
is unsigned, thus%ld
is double wrong: wrong length modifier and wrong format conversion specifier. In case you wonder,%zd
is forssize_t
(which is signed).Yes: use the
z
length modifier:The other length modifiers that are available are
hh
(forchar
),h
(forshort
),l
(forlong
),ll
(forlong long
),j
(forintmax_t
),t
(forptrdiff_t
), andL
(forlong double
). See §7.19.6.1 (7) of the C99 standard.