let’s say I want to select the behaviour of a certain preprocessor directive evaluating at compile time the concatenation of a constant string and the result of another macro.
#define CASE1 text1
#define CASE2 text2
#define CASE3 text3
#define SCENARIO 3
/** the following won't work - for examplification purposes only**/
#define FUNCTION CASE##SCENARIO
/** whenever I write FUNCTION, I expect to see text3 **/
I am having an hard time thinking of a viable solution, as the preprocessor is a one-pass beast. Is that even feasible ?
It’s possible, you just need to add some extra layers of macros. The key is that when you use the token-pasting operator
##, the preprocessor will not expand its operands. But, if you add another layer of macros, the preprocessor will expand those arguments. For example:When the preprocessor expands
FUNCTION, it expandsTOKENPASTE. When it expandsTOKENPASTE, it expands its arugments (soSCENARIOgets replaced by3), since neither of its arguments are operands of the token-pasting operator. Next, it expandsTOKENPASTE_HELPER, which does the actual token pasting to makeCASE3. Finally, it expands theCASE3macro to gettext3.