Home > OS >  Expand the concatenated text to be a macro and then expand the Macro again
Expand the concatenated text to be a macro and then expand the Macro again

Time:01-21

#include <stdio.h>

#define X 2
#define N_1_T 50
#define N_2_T 49
#define PRINT() printf("id: %d", N_ ## X ## _T)

int main(void)
{
    PRINT();
    return 0;
}

I want N_ ## X ## _T to be expanded to N_2_T when I have the Macro #define X 2. If I change the Macro definition of X to be #define X 1, N_ ## X ## _T should be expanded to N_1_T.

But I do not know how to do this. I have searched and read many pages, but I just do not get what I should do to achieve the desired result.

Please help, thank you.

CodePudding user response:

To achieve what you want, the X macro must be expanded to the pre-processor token 2 before concatenation, so the macro containing the ## must get passed an expanded 2. It is very similar to this: Stringification - how does it work?

You can solve this with a number of helper macros that enforce rescanning of the pp tokens:

#include <stdio.h>

#define X 2
#define N_1_T 50
#define N_2_T 49

#define CONCAT(n) N_ ## n ## _T
#define GET_ID(n) CONCAT(n)
#define PRINT() printf("id: %d", GET_ID(X))

int main(void)
{
    PRINT();
    return 0;
}

Output:

id: 49
  •  Tags:  
  • Related