What I'm trying to do is to #define
a macro:
#define a(2)
and later use it inside a string literal: string = "a";
.
I want that string to be interpreted not as string but to get the value of a
, i.e. 2. I didn't succeed, can anybody help?
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.
We can create two or more than two strings in macro, then simply write them one after another to convert them into a concatenated string. The syntax is like below: #define STR1 "str1" #define STR2 " str2" #define STR3 STR1 STR2 //it will concatenate str1 and str2.
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.
“Stringification” means turning a code fragment into a string constant whose contents are the text for the code fragment. For example, stringifying foo (z) results in “foo (z)” . In the C & C++ preprocessor, stringification is an option available when macro arguments are substituted into the macro definition.
#define STRINGIFY2(X) #X #define STRINGIFY(X) STRINGIFY2(X) #define A 2
Then STRINGIFY(A)
will give you "2"
. You can concatenate it with other string literals by putting them side by side.
"I have the number " STRINGIFY(A) "."
gives you "I have the number 2."
.
No, you cannot do macro expansion INSIDE string literals (i.e. having the preprocessor to look inside literals for macros to expand).
You can have a macro expansion to produce a string literal using the stringify operator (#
). But that's a different thing.
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