What is unquoted `PRIu32` in printf in C?
Asked Answered
P

1

16

I am looking at the following code:

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

int main()
{
    uint32_t total = 0;

    printf("\tTotal: %"PRIu32"\n\n", total);
    return total;
}

How does PRIu32 fit into the printf syntax? I mean, I sorta can guess that, Iu32 probably means "Integer unsigned 32-bit". However, I am not sure which form found in man 3 printf would accommodate variables outside quotation marks-- and how this can generalize to other statements outside quotation marks.

Pony answered 28/8, 2017 at 15:46 Comment(4)
try gcc prog.c -E -P if You use gcc. Also String literal sequences like "\tTotal: %" "u" "\n\n" are combined in pre-compilation preprocessing.Drawback
@Drawback Running $ gcc progc -E -P test.c gives me clang: error: no such file or directory: 'progc'. What is that command supposed to do?Pony
Replace prog.c with the C source you are trying to compile.Drawback
@Drawback Wow, that cool! I think I'll use it in the future, any time I don't know what some variable is. p.s., it was because your post had the missing ., that I didn't interpret it correctly.Pony
E
25

It's a format macro constant.

They are used for portable formatting of values along different platforms where sizes of the primitive number types might differ.

The one in the question is the format to print unsigned 32-bit integers in decimal format.

These macros works because C concatenates consecutive constant string literals. For example the three strings "\tTotal: %" "u" "\n\n" will be concatenated into the single string "\tTotal: %u\n\n" by the compiler.

Excommunicatory answered 28/8, 2017 at 15:49 Comment(6)
thats not the same number of quotes as in the questionMonnet
@Monnet Hey, stop being pedantic. His comment alone was enough to answer my question already...Pony
@Monnet The macros are defined so they are expanded as strings, e.g. #define PRIu32 "u"Excommunicatory
I am not being pedantic, I am curious as to why it works. This answer is good but doesnt explain whats happening in your caseMonnet
@Someprogrammerdude if its defined as the string "u", shouldn't we require the + operator to concatenate it to the string we pass to printf? Or does C not require a + for concatenation?Bodycheck
@Bodycheck You can't concatenate strings using +. But consecutive literal strings will be concatenated by the compiler. As mentioned in the answer.Excommunicatory

© 2022 - 2024 — McMap. All rights reserved.