0

I have some macros in code

#define NUM_IN 3

#define NUM_1 1
#define NUM_2 2
#define NUM_3 3

#define MY(NUMBER) NUM_##NUMBER

so if I'm calling the macro

MY(NUM_IN)

I'm expecting after preprocessing result as 3 but I'm getting NUM_NUM_IN

So, what I should do so preprocessor will take input as

step 1

MY(NUM_IN)

step 2

MY(3)

step 3

NUM_3

step 4

3

Please let me know what I'm missing. I am new to stackoverflow so please guide me to the proper channel if I am wrong.
Thanks

3 Answers3

2

Add one layer of indirection:

#define CAT_(a, b) a ## b     /* Pastes  */
#define CAT(a, b)  CAT_(a, b) /* Expands */

#define MY(NUMBER) CAT(NUM_, NUMBER)
Quentin
  • 62,093
  • 7
  • 131
  • 191
2

Add a layer of indirection:

#define NUM_IN 3

#define NUM_1 1
#define NUM_2 
#define NUM_3 3

#define CAT_(X,Y) X##Y
#define MY(NUMBER) CAT_(NUM_,NUMBER)

MY(NUM_IN)
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
1

Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringized or pasted with other tokens.1

So, in MY(NUM_IN), NUM_IN will not expanded. You need to define an another macro for concatenation

#define PASTER(n) NUM_ ## n
#define MY(NUMBER) PASTER(NUMBER)

1. GCC docs: 3.5 Concatenation

haccks
  • 104,019
  • 25
  • 176
  • 264