Home >Backend Development >C++ >Can Recursive Macros Be Achieved in C/C ?
Recursive Macros in C/C : Myth or Reality?
Despite the absence of direct recursive macros in C/C , clever workarounds exist to achieve a semblance of recursive functionality.
Recursive Macro Emulation Using Deferred Expressions and Indirection
One approach involves using deferred expressions and indirection. By employing the DEFER and EMPTY macros, we can defer evaluation of our macro and prevent it from being painted blue by the preprocessor. This circumvents the recursive expansion limitation.
For instance, consider the following macro:
#define pr_id() pr #define pr(n) ((n==1)? 1 : DEFER(pr_id)()(n-1))
By leveraging this macro, we gain the ability to recursively call pr(n) in a roundabout manner. However, this technique requires multiple preprocessor scans for complete expansion.
Recursive Macro via Expression Evaluation
Another method involves utilizing a series of expression evaluation macros, such as EVAL1 to EVAL5, to simulate recursive behavior.
For example, to define a recursive repeat macro, we can utilize the following syntax:
#define REPEAT(count, macro, ...) \ WHEN(count) \ ( \ OBSTRUCT(REPEAT_INDIRECT) () \ ( \ DEC(count), macro, __VA_ARGS__ \ ) \ OBSTRUCT(macro) \ ( \ DEC(count), __VA_ARGS__ \ ) \ )
By applying multiple expansions, we can achieve recursive-like behavior, as demonstrated by the following code:
EVAL(REPEAT(8, M, ~)) // Output: 0 1 2 3 4 5 6 7
Code Execution Issue
The code mentioned in your question will not execute due to the improper use of the cout object. The correct syntax should be:
cout << "result: " << pr(5) << endl;
Replace the < and > symbols with << to enable proper output in C .
The above is the detailed content of Can Recursive Macros Be Achieved in C/C ?. For more information, please follow other related articles on the PHP Chinese website!