How to evaluate a nested preprocessor macro

let's say I want to choose the behavior of a particular preprocessor directive, evaluating the compaction of a constant string and the result of another macro at compile time.

#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 **/ 

It's hard for me to think of a viable solution, because the preprocessor is a one-pass beast. Is it possible?

+4
source share
1 answer

Perhaps you just need to add a few extra macros. The key is that when using the ## operator to work with the token, the preprocessor will not expand its operands. But if you add another layer of macros, the preprocessor will expand these arguments. For instance:

 #define CASE1 text1 #define CASE2 text2 #define CASE3 text3 #define SCENARIO 3 #define TOKENPASTE_HELPER(x, y) x ## y #define TOKENPASTE(x, y) TOKENPASTE_HELPER(x, y) #define FUNCTION TOKENPASTE(CASE, SCENARIO) 

When the preprocessor extends FUNCTION , it extends TOKENPASTE . When it expands with TOKENPASTE , it expands its formulas (therefore, SCENARIO is replaced with 3 ), since none of its arguments is an operand of the marker operator. Then it extends TOKENPASTE_HELPER , which makes the actual insertion of the marker to make CASE3 . Finally, he extends the CASE3 macro to get text3 .

+11
source

Source: https://habr.com/ru/post/1442133/


All Articles