Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format specifier to portably print std::uint64_t variable in C++11

What is the format specifier to print a value of type std::uint64_t (from <cstdint>) using functions from the std::printf() family in C++?

C99 has PRIu64 (from <inttypes.h>) but it's not entirely clear to me that PRIu64 is valid C++11, although I could find hints that it may be.

Without PRIu64, and as far as I can tell, there's no single format specifier that will work in all cases:

  • On 32-bit platforms, std::uint64_t is going to be defined as unsigned long long and the format specifier will be %llu.
  • On 64-bit platforms, std::uint64_t is going to be defined as unsigned long and the format specifier will be %lu.
  • However with Visual Studio, %llu works in both cases.
like image 688
François Beaune Avatar asked Dec 08 '22 12:12

François Beaune


1 Answers

PRIu64 is still what you will use in C++. Per [cinttypes.syn] PRIu64

[...]

#define PRIuN see below

[...]

The contents and meaning of the header <cinttypes> are the same as the C standard library header <inttypes.h> [...]

So it exists and has the same behavior that it does in the C ISO/IEC 9899:2011 standard.

like image 143
NathanOliver Avatar answered May 12 '23 15:05

NathanOliver