1

Consider the following code:

#define TOTO 0xAA
#define TITI 0xBB

unsigned char val0xAA[] = {1, 2, 3};
unsigned char val0xBB[] = {4, 5, 6};

// Macro using Token pasting
#define VAL(_x_) val##_x_

void foo(void)
{
    // Silly attempt to abuse preprocessor
    unsigned char *tab1 = VAL(TOTO);
    unsigned char *tab2 = VAL(TITI);
}

I would like VAL(TOTO) macro to expand to val0xAA but it actually expands to valTOTO and the compilation fails.

The question is: Is it possible to "force/prioritize" the evaluation of TOTO before the Token pasting evaluation ?

n0p
  • 3,399
  • 2
  • 29
  • 50

1 Answers1

3

Yes, it's a common trick. Just add another layer.

#define TOTO 0xAA
#define TITI 0xBB

unsigned char val0xAA[] = {1, 2, 3};
unsigned char val0xBB[] = {4, 5, 6};

// Macro using Token pasting
#define VAL1(_x_) val##_x_
#define VAL(_x_) VAL1(_x_) // expand and pass to VAL1 to concatenate 

void foo(void)
{
    // Silly attempt to abuse preprocessor
    unsigned char *tab1 = VAL(TOTO);
    unsigned char *tab2 = VAL(TITI);
}
DeiDei
  • 10,205
  • 6
  • 55
  • 80