Home > Backend Development > C++ > How Can Recursion Be Emulated with C/C Macros?

How Can Recursion Be Emulated with C/C Macros?

Linda Hamilton
Release: 2024-12-07 08:53:11
Original
998 people have browsed it

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))
Copy after login

Execution Process

When pr(5) is encountered, the following steps occur:

  1. pr(5) expands to ((5 == 1) ? 1 : DEFER(pr_id)()(5 - 1)).
  2. The preprocessor paints pr(5) blue (disabling context), preventing it from expanding further.
  3. DEFER(pr_id)()(5 - 1) becomes OBSTRUCT(pr_id)()(5 - 1) and pr_id () is painted blue.
  4. EXPAND(pr(5)) expands to ((5 == 1) ? 1 : ((5 - 1 == 1) ? 1 : DEFER(pr_id)()(5 - 1 - 1)))
  5. Additional expansions are required to complete the recursion.

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
Copy after login

This macro can be used as follows:

EVAL(REPEAT(8, M, ~)) // 0 1 2 3 4 5 6 7
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template