C preprocessor macro expansion

Viewed 5666

I have difficulty understanding how rewriting rules are applied by the C preprocessor in the following context. I have the following macros:

#define _A(x) "A" _##x
#define _B(x) "B" _##x
#define X(x) _##x

The idea is that each of these macros uses the concatenation to create a new expression, which can itself be a macro — if its a macro, I'd like it to be expanded:

Now, the following expands just like I expect:

X(x)       expands to _x
X(A(x))    expands to "A" _x
X(A(B(x))) expands to "A" "B" _x

However, once the same macro is used more then once, the expansion stops:

X(A(A(x)))       expands to "A" _A(x), expected "A" "A" _x
X(B(B(x)))       expands to "B" _B(x), expected "B" "B" _x
X(A(B(A(x))))    expands to "A" "B" _A(x), expected "A" "B" "A" _x 
X(A(B(A(B(x))))) expands to "A" "B" _A(B(x)), expected "A" "B" "A" "B" _x 

I guess that there is some sort of "can expand same-named macro only once" rule at play here? Is there something I can do to get the macros to expand the way I want?

2 Answers
Related