2

I want create an object-like macro from the concatenation of token and macro. I have this code:

#define alfa vita
/* Code below is broken. */
#define gamma delta##alfa
gamma

The gamma is replaced with deltaalfa. I want it replaced with deltavita. How can I do this?

I don't want the gamma to be a function-like macro.


What are the applications of the ## preprocessor operator and gotchas to consider?
This question is very broad. It isn't focused on my problem and the first answer doesn't address it either.

Community
  • 1
  • 1
Michas
  • 8,534
  • 6
  • 38
  • 62

1 Answers1

6

You must perform a double macro expansion like so:

#define alfa vita

#define concat2(a,b) a ## b
#define concat(a,b) concat2(a,b)
#define gamma concat(delta, alfa)

gamma

The operands of the stringification (#) and token pasting (##) operators are not first expanded. As a special case, expansion of a function-style macro proceeds by first expanding the arguments except where they are operands of the # or ## operator, then substituting them into the macro body, then rescanning for substitutions.

The double-expansion approach above works because the arguments of the concat() macro are not operands of ## (or #). They are therefore expanded before being substituted into that macro's body to yield

concat2(delta, vita)

Upon rescanning, that is expanded further to

delta ## vita

(regardless of any macro definition for the symbol vita), which is then pasted together into a single token to yield the result.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157