4

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.
François Beaune
  • 4,270
  • 7
  • 41
  • 65
  • 4
    *On 64-bit platforms, std::uint64_t is going to be defined as unsigned long and the format specifier will be %lu.* that is only true for *nix systems. Windows still uses a 32 bit long in 64 bit systems. – NathanOliver May 16 '19 at 16:24
  • 1
    `` should have that macro too if I'm not mistaken. Edit: And [cppreference](https://en.cppreference.com/w/cpp/header/cinttypes) verifies it. – StoryTeller - Unslander Monica May 16 '19 at 16:25
  • @NathanOliver Indeed, because Windows is LLP64, hence why `%llu` is always the right specifier with Visual Studio. – François Beaune May 16 '19 at 16:27
  • 1
    @rustyx I'm posting this question precisely because `%llu` doesn't always work. – François Beaune May 16 '19 at 16:27
  • 1
    Possibly relevant, and maybe even dupe: https://stackoverflow.com/questions/8132399/how-to-printf-uint64-t-fails-with-spurious-trailing-in-format – Andrew Henle May 16 '19 at 16:30
  • @AndrewHenle Somewhat related but clearly not dupe. Also, this question is specifically about C++11 while the one you linked is about C99. There are many subtle differences between the two when it comes to this topic. – François Beaune May 16 '19 at 19:01

1 Answers1

14

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.

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402