Home >Backend Development >C++ >How Can Recursion Be Emulated with C/C Macros?
Recursive Macros in C/C
Macros in C/C do not support direct recursion. However, it is possible to emulate recursion through a combination of preprocessing techniques and indirection.
Example of a Recursive-like Macro
The following macro simulates recursion using deferred expressions and indirection:
#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))
Execution Process
When pr(5) is encountered, the following steps occur:
Recursive Repeat Macro
A more complex example of a recursive-like macro is a repeat macro that executes a specific code block a given number of times:
#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
This macro can be used as follows:
EVAL(REPEAT(8, M, ~)) // 0 1 2 3 4 5 6 7
Limitations
While emulating recursion through macros is possible, it is generally considered a bad practice due to potential performance implications and code readability issues. Modern C offers alternative mechanisms for recursion, such as lambda expressions and template metaprogramming.
The above is the detailed content of How Can Recursion Be Emulated with C/C Macros?. For more information, please follow other related articles on the PHP Chinese website!