4

Consider the following code:

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

void main(void)
{
    int32_t a = 44;

    fprintf(stdout, "%d\n", a);
    fprintf(stdout, "%"PRId32"\n", a);
}

When is it better to use %d and when would it be better to use "%"PRId32? How do both of those format characters differ? Does this have something to do with how int32_t is typedeffed on your hardware/machine?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • Note for C++ users looking at this question: `"%"PRId32` is fine in C, but for C++11 and later you need a space between, like `"%" PRId32`, or else `"%"PRId32` is a user-defined literal instead of two separate tokens, which will probably cause compile errors. – aschepler Jan 19 '19 at 14:30

2 Answers2

7

Use %d for int and PRId32 for int32_t.

Maybe on your platform int32_t is just a typedef for int but this is not true in general. Using a wrong specifier invokes undefined behavior and should be avoided.

As pointed out by @EricPostpischil note that %d is used inside a quoted format string while PRId32 is used outside. The reason for this is that PRId32 is a macro which expands to a string literal and is then concatenated.

Osiris
  • 2,783
  • 9
  • 17
4

The type int is required to have at least 16 bits of value representation, although on most desktop computers and compilers it will have 32 bits. So int might in general be the same as int16_t, int32_t, int64_t, or none of the above.

Use "%d" for variables of type int, and use "%" PRId32 for variables of type int32_t.

aschepler
  • 70,891
  • 9
  • 107
  • 161