Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using #define and # for stringizing to convert another macro constant to string

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?

like image 476
beta_me me_beta Avatar asked Jul 02 '26 18:07

beta_me me_beta


1 Answers

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.

like image 106
CRM Avatar answered Jul 05 '26 12:07

CRM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!