With reference to this question Quote macro for defining string, Idea is that I want to print the value of a macro constant, say for the following code:
#include<stdio.h>
#define X 4
#define Tostring(x) #x
main()
{
printf(Tostring(X));
}
It is printng X instead of 4, but with Quote macro for defining string I know how to correct it, but can someone explain what exactly is gong on here?
To print 4 as you wish you can one of these:
Stringizing the result:
#include<stdio.h>
#define Tostring(x) str(x)
#define str(x) #x
#define X 4
int main()
{
printf(Tostring(X));
}
or using function like macros to convert X to int:
#include<stdio.h>
#define X 4
#define Tostring(x)(X)
int main()
{
printf("%d\n", Tostring(X));
}
The first example is one of the examples that is given in documentation. There it is stated that two levels of macros shall be used if you want to stringize the result of the expansion of a macro. The result of the expansion is the following:
Tostring (X) -> Tostring(4) -> str (4) -> "4"
In the second example you are relating the argument of Tostring macro with the X from the #define X 4 and thus you can print the value as an int.
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