Printing values with C Format Strings

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 to long or unsigned long, respectively.
  • 64-bit length: use %lld for signed and %llu for unsigned. Cast to long long or unsigned long long, respectively.
  • size_t: use %zu.
  • Hex:
    • Until 16-bit length use %x.
    • 32-bit length use %lx and cast to unsigned long.
    • 64-bit length use %llx and cast to unsigned long long.

Individual cases:

ValueFormat stringReason
char"%d"Is promoted to int.
short"%d"Is promoted to int. Minimal width: 16bit.
int%dMinimal width: 16bit (int16_t).
long%d or %ldMinimal width: 32bit (int32_t).
long long%lldMinimal width: 64bit (int64_t).
int8_t%dIs promoted to int.
int16_t%dIs promoted to int.
int32_t%ldCast to long required.
int64_t%lldCast to long long required.
unsigned char%dIs promoted to int
unsigned short%u
unsigned int%uMinimal width: 16bit (uint16_t)
unsigned long%luMinimal width: 32bit (uint32_t)
unsigned long long%lluMinimal width: 64bit (uint64_t)
uint8_t%u or %dIs promoted to int.
uint16_t%uIs promoted to int.
uint32_t%luCast to unsigned long required.
uint64_t%lluCast to unsigned long long required.
size_t%zu
float%f or %gPromoted 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 %lXCast to unsigned long required.
hex(uint64_t)%llx or %llXCast to unsigned long long required.

For more information see this manpage.