1
#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.

Wu Xiliang
  • 316
  • 3
  • 10
  • Please don't spam unrelated language tags. Your program is written in either C, or in C++. Not both. – Some programmer dude Jan 20 '22 at 12:59
  • As for solving your problem with the macro, for only two alternatives a conditional expression (with some comments about it) should suffice. Otherwise for only a handful of alternatives, a function and `switch` is good (don't forget the `default` case!). But for more you should probably resort to arrays to translate one value to another (with some added bounds-checking). – Some programmer dude Jan 20 '22 at 13:02
  • @Someprogrammerdude Right. But the macro should work in both C and C++, I think. I know there are other ways to finish this kind of job, but I am just curious to know whether macro could do the same thing. Thank you for any help. – Wu Xiliang Jan 20 '22 at 13:10

1 Answers1

4

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
Lundin
  • 195,001
  • 40
  • 254
  • 396