0

Consider the following snippet, compiled with gcc -Wall for two different architectures:

int64_t x;
printf("A: %ld\n", x);
printf("B: %lld\n", x);

When compiling for a 32 bit machine, the compiler complains about "A":

format '%ld' expects argument of type 'long int', but argument 2 has type 'int64_t' {aka 'long long int'}

When compiling for a 64 bit machine, the compiler complains about "B":

format '%lld' expects argument of type 'long long int', but argument 2 has type 'int64_t' {aka 'long int'}

The question: What is a sensible machine-independent way to printf() int64_t?

fearless_fool
  • 33,645
  • 23
  • 135
  • 217

1 Answers1

2

The header inttypes.h contains portable conversion specifiers for printf and scanf family of functions. (It also internally includes stdint.h.)

#include <inttypes.h>

int64_t x = ...;
printf("%"PRIi64, x);

See the C standard C17 7.8.1 for details.

Lundin
  • 195,001
  • 40
  • 254
  • 396