Matt Joiner
Matt Joiner

Reputation: 118510

Printf with typedef integers, especially 64bit

Consider this code:

typedef int64_t Blkno;
#define BLKNO_FMT "%lld"
printf(BLKNO_FMT, (Blkno)some_blkno);

This works well and fine on x86. On x64, int64_t is actually a long, rather than a long long, and while long and long long are the same size on x64, the compiler generates an error:

src/cpfs/bitmap.c:14: warning: format ‘%lld’ expects type ‘long long int’, but argument 6 has type ‘Blkno’

  1. How can I tell printf that I'm passing a 64bit type?
  2. Is there some better way to standardize specs for user types than using a #define like BLKNO_FMT as above?

Upvotes: 5

Views: 3020

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215259

These types are not 64-bit types. They're platform-specific. The only portable way to print them is to cast to intmax_t or uintmax_t and use the correct format specifiers for to print those types.

Upvotes: 0

jfs
jfs

Reputation: 414215

Use PRId64 from inttypes.h.

Blkno is not a very good type name. BLKNO_FMT could be replaced by PRIdBLKNO.

#include <inttypes.h>
#include <stdio.h>

typedef int64_t Blkno;
#define PRIdBLKNO PRId64

int main(void) {
  printf("%" PRIdBLKNO "\n", (Blkno)1234567890);
  return 0;
}

Upvotes: 10

Related Questions