Home >Backend Development >C++ >Can Recursive Macros Be Implemented in C/C ?

Can Recursive Macros Be Implemented in C/C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 09:05:12320browse

Can Recursive Macros Be Implemented in C/C  ?

Exploring Recursive Macros in C/C : The Art of Expansion

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:

  1. Obstruct Self-Expansion: Prevent the macro from halting its expansion by creating a disabling context.
  2. Indirection: Use indirection to defer the expansion to a later stage.
  3. Expansion: Apply multiple scans to complete the expansion 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn