Option 1:
Since on most (if not all?) systems, the PRIuPTR
printf format string from is also long enough to hold a size_t
type, I recommend using the following defines for size_t
printf format strings.
However, it is important that you verify this will work for your particular architecture (compiler, hardware, etc), as the standard does not enforce this.
#include <inttypes.h>
// Printf format strings for `size_t` variable types.
#define PRIdSZT PRIdPTR
#define PRIiSZT PRIiPTR
#define PRIoSZT PRIoPTR
#define PRIuSZT PRIuPTR
#define PRIxSZT PRIxPTR
#define PRIXSZT PRIXPTR
Example usage:
size_t my_variable;
printf("%" PRIuSZT "\n", my_variable);
Option 2:
Where possible, however, just use the %zu
"z" length specifier, as shown here, for size_t
types:
Example usage:
size_t my_variable;
printf("%zu\n", my_variable);
On some systems, however, such as STM32 microcontrollers using gcc as the compiler, the %z
length specifier isn't necessarily implemented, and doing something like printf("%zu\n", my_size_t_num);
may simply end up printing out a literal "%zu" (I personally tested this and found it to be true) instead of the value of your size_t
variable.
Option 3:
Where you need it to be absolutely guaranteed to work, however, or where you aren't sure about your particular architecture, just cast and print as a uint64_t
and be done, as this is guaranteed to work, but requires the extra step of casting.
Example usage:
#include <stdint.h> // for uint64_t
#include <inttypes.h> // for PRIu64
size_t my_variable;
printf("%" PRIu64 "\n", (uint64_t)my_variable);
Sources Cited:
- http://www.cplusplus.com/reference/cstdio/printf/
- http://www.cplusplus.com/reference/cinttypes/
- http://www.cplusplus.com/reference/cstdint/