Can Recursive Macros Exist?
While macros lack inherent recursive capabilities in C/C , there exists a path to achieving recursive-like behavior. Using a combination of deferred expressions and indirection, one can create elaborate macros that simulate recursion.
How it Works
To craft a recursive macro, we must embrace a multi-step process:
Example: Recursive Repeat Macro
Here's an illustration of a recursive repeat macro:
#define REPEAT(count, macro, ...) \ WHEN(count) \ ( \ OBSTRUCT(REPEAT_INDIRECT) () \ ( \ DEC(count), macro, __VA_ARGS__ \ ) \ OBSTRUCT(macro) \ ( \ DEC(count), __VA_ARGS__ \ ) \ )
This macro can be invoked like this:
EVAL(REPEAT(8, M, ~)) // Outputs: 0 1 2 3 4 5 6 7
Sample Execution Issue
Your provided code:
# define pr(n) ((n==1)? 1 : pr(n-1)) void main () { int a=5; cout<<"result: "<< pr(5) <<endl; getch(); }
does not execute due to a recursive macro issue. The pr macro relies solely on recursion, leading to infinite expansion.
Solution
To fix this issue, you could use the following non-recursive version of the macro:
#define fact(n) ((n == 1)? 1 : n * fact(n - 1))
The above is the detailed content of Can Recursive Macros Be Implemented in C/C ?. For more information, please follow other related articles on the PHP Chinese website!