While macros don't directly expand recursively, there are clever techniques to achieve similar functionality.
We can use deferred expressions and indirection to prevent the preprocessor from disabling the macro during expansion. Here's an example of creating a recursive pr macro:
#define EMPTY(...) #define DEFER(...) __VA_ARGS__ EMPTY() #define OBSTRUCT(...) __VA_ARGS__ DEFER(EMPTY)() #define EXPAND(...) __VA_ARGS__ #define pr_id() pr #define pr(n) ((n==1)? 1 : DEFER(pr_id)()(n-1))
This macro expands as follows:
pr(5) -> ((5==1)? 1 : pr_id()(4)) EXPAND(pr(5)) -> ((5==1)? 1 : ((4==1)? 1 : pr_id()(3)))
Using these techniques, we can create a recursive REPEAT macro:
#define REPEAT(count, macro, ...) \ WHEN(count) \ ( \ OBSTRUCT(REPEAT_INDIRECT) () \ ( \ DEC(count), macro, __VA_ARGS__ \ ) \ OBSTRUCT(macro) \ ( \ DEC(count), __VA_ARGS__ \ ) \ ) #define REPEAT_INDIRECT() REPEAT #define M(i, _) i EVAL(REPEAT(8, M, ~)) // 0 1 2 3 4 5 6 7
While these workarounds enable recursive macros, it's important to note that they can be complex and may not work in all cases. It's recommended to approach recursive macro usage with caution and consider alternatives such as functions or template metaprogramming when appropriate.
The above is the detailed content of Can We Create Recursive Macros in C/C Preprocessing?. For more information, please follow other related articles on the PHP Chinese website!