C preprocessor has a feature called stringification. It's a feature that allows to create a (narrow) string literal from a macro parameter. It can be used like this:
#define PRINTF_SIZEOF(x) printf("sizeof(%s) == %d", #x, sizeof(x))
/* stringification ^^ */
Usage example:
PRINTF_SIZEOF(int);
...might print:
sizeof(int) == 4
How to create a wide string literal from a macro parameter? In other words, how can I implement WPRINTF_SIZEOF
?
#define WPRINTF_SIZEOF(x) wprintf( <what to put here?> )
Thank you. The number-sign or "stringizing" operator ( #) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.
When a macro parameter is used with a leading #, the preprocessor replaces it with the literal text of the actual argument, converted to a string constant. Unlike normal parameter replacement, the argument is not macro-expanded first. This is called stringification .
Sometimes you may want to convert a macro argument into a string constant. Parameters are not replaced inside string constants, but you can use the ‘ # ’ preprocessing operator instead. When a macro parameter is used with a leading ‘ # ’, the preprocessor replaces it with the literal text of the actual argument, converted to a string constant.
This is called stringification . There is no way to combine an argument with surrounding text and stringify it all together. Instead, you can write a series of adjacent string constants and stringified arguments. The preprocessor will replace the stringified arguments with string constants.
In order to produce a wide string literal from a macro argument, you need to combine stringification with concatenation.
WPRINTF_SIZEOF
can be defined as:
#define WPRINTF_SIZEOF(x) wprintf(L"sizeof(%s) == %d", L ## #x, sizeof(x))
/* concatenation ^^ ^^ stringification */
In order to (arguably) increase readability, you can extract this trick into a helper macro:
#define WSTR(x) L ## #x
#define WPRINTF_SIZEOF(x) wprintf(L"sizeof(%s) == %d", WSTR(x), sizeof(x))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With