Mmh, who are you PRIu64?

CMacrosPrintf

C Problem Overview


I am new to C and I am confronted with:

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

int main(void)
{
    uint64_t foo = 10;
    printf("foo is equal to %" PRIu64 "!\n", foo);
    
    return 0;
}

And it works! I don't understand why? Can somebody help me about this? Thanks a lot! torr

C Solutions


Solution 1 - C

PRIu64 is a format specifier, introduced in C99, for printing uint64_t, where uint64_t is (from linked reference page):

>unsigned integer type with width of ... 64 bits respectively (provided only if the implementation directly supports the type)

PRIu64 is a string (literal), for example the following:

printf("%s\n", PRIu64);

prints llu on my machine. Adjacent string literals are concatenated, from section 6.4.5 String literals of the C99 standard:

>In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and wide string literal tokens are concatenated into a single multibyte character sequence. If any of the tokens are wide string literal tokens, the resulting multibyte character sequence is treated as a wide string literal; otherwise, it is treated as a character string literal.

This means:

printf("foo is equal to %" PRIu64 "!\n", foo);

(on my machine) is the same as:

printf("foo is equal to %llu!\n", foo);

See http://ideone.com/jFvKR9 .

Solution 2 - C

You can also use it to print pointer value. Example from LTP BPF patchset:

static uint64_t *val;
...
tst_res(TFAIL, "dst(r7) = %"PRIu64", but should be zero", *val);

prints: dst(r7) = 18446744073709551615, but should be zero

NOTE: tst_res() is a printf like function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontorrView Question on Stackoverflow
Solution 1 - ChmjdView Answer on Stackoverflow
Solution 2 - CpevikView Answer on Stackoverflow