In order to ensure compiler and platform portability use the following rules for C format strings.
Assumption: A value of 16/32 or 64bit length needs to be printed with a C99 format string.
- Until 16-bit length: use
%d
for signed and%u
for unsigned. No casts are needed. - 32-bit length: use
%ld
for signed and%lu
for unsigned. Cast tolong
orunsigned long
, respectively. - 64-bit length: use
%lld
for signed and%llu
for unsigned. Cast tolong long
orunsigned long long
, respectively. - size_t: use
%zu
. - Hex:
- Until 16-bit length use
%x
. - 32-bit length use
%lx
and cast tounsigned long
. - 64-bit length use
%llx
and cast tounsigned long long
.
- Until 16-bit length use
Individual cases:
Value | Format string | Reason |
---|---|---|
char | "%d" | Is promoted to int . |
short | "%d" | Is promoted to int . Minimal width: 16bit. |
int | %d | Minimal width: 16bit (int16_t ). |
long | %d or %ld | Minimal width: 32bit (int32_t ). |
long long | %lld | Minimal width: 64bit (int64_t ). |
int8_t | %d | Is promoted to int . |
int16_t | %d | Is promoted to int . |
int32_t | %ld | Cast to long required. |
int64_t | %lld | Cast to long long required. |
unsigned char | %d | Is promoted to int |
unsigned short | %u | |
unsigned int | %u | Minimal width: 16bit (uint16_t ) |
unsigned long | %lu | Minimal width: 32bit (uint32_t ) |
unsigned long long | %llu | Minimal width: 64bit (uint64_t ) |
uint8_t | %u or %d | Is promoted to int . |
uint16_t | %u | Is promoted to int . |
uint32_t | %lu | Cast to unsigned long required. |
uint64_t | %llu | Cast to unsigned long long required. |
size_t | %zu | |
float | %f or %g | Promoted to double for printing (compiler dependent). |
double | %f or %g | |
void * | %p | |
hex(uint8_t) | %x or %X | |
hex(uint16_t) | %x or %X | |
hex(uint32_t) | %lx or %lX | Cast to unsigned long required. |
hex(uint64_t) | %llx or %llX | Cast to unsigned long long required. |
For more information see this manpage.