Issue
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
?
Solution
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.
Answered By - Lundin Answer Checked By - David Marino (WPSolving Volunteer)