简体   繁体   中英

How to print uint32_t variables value via wprintf function?

It is a well-known fact that to print values of variables that type is one of fixed width integer types (like uint32_t ) you need to include cinttypes (in C++) or inttypes.h (in C) header file and to use format specifiers macros like PRIu32 . But how to do the same thing when wprintf function is used? Such macro should expand as a string literal with L prefix in that case.

If this will work or not actually depends on which standard of C the compiler is using.

From this string literal reference

Only two narrow or two wide string literals may be concatenated. ( until C99 )

and

If one literal is unprefixed, the resulting string literal has the width/encoding specified by the prefixed literal. If the two string literals have different encoding prefixes, concatenation is implementation-defined. ( since C99 )

[Emphasis mine]

So if you're using an old compiler or one that doesn't support the C99 standard (or later) it's not possible. Besides fixed-width integer types was standardized in C99 so the macros don't really exist for such old compilers, making the issue moot.

For more modern compilers which support C99 and later, it's a non-issue since the string-literal concatenation will work and the compiler will turn the non-prefixed string into a wide-character string, so doing eg

wprintf(L"Value = %" PRIu32 "\n", uint32_t_value);

will work fine.


If you have a pre-C99 compiler, but still have the macros and fixed-width integer types, you can use function-like macros to prepend the L prefix to the string literals. Something like

#define LL(s) L ## s
#define L(s) LL(s)

...

wprintf(L"Value = %" L(PRIu32) L"\n", uint32_t_value);

Not sure where the problem is, but here (VS 2015) both

wprintf(L"AA %" PRIu32 L" BB", 123);

and

printf("AA %" PRIu32 " BB", 123);

compile correctly and give following output:

AA 123 BB

Even if your compiler does not support concatenation of differently-prefixed literals, you can always widen a narrow one:

#define WIDE(X) WIDE2(X)
#define WIDE2(X) L##X

wprintf(L"%" WIDE(PRIu32), foo);

Demo

A (weaker) alternative to using the macros from <inttypes.h> is to convert/cast the the fixed width type to an equivalent or larger standard type.

wprintf(L"%lu\n", 0ul + some_uint32_t_value);
// or 
wprintf(L"%lu\n", (unsigned long) some_uint32_t_value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM