Home > Backend Development > C++ > Can We Create Recursive Macros in C/C Preprocessing?

Can We Create Recursive Macros in C/C Preprocessing?

Barbara Streisand
Release: 2024-12-09 11:47:16
Original
207 people have browsed it

Can We Create Recursive Macros in C/C   Preprocessing?

Can We Have Recursive Macros?

While macros don't directly expand recursively, there are clever techniques to achieve similar functionality.

Workaround for Recursive Macros

We can use deferred expressions and indirection to prevent the preprocessor from disabling the macro during expansion. Here's an example of creating a recursive pr macro:

#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

This macro expands as follows:

pr(5) -> ((5==1)? 1 : pr_id()(4))
EXPAND(pr(5)) -> ((5==1)? 1 : ((4==1)? 1 : pr_id()(3)))
Copy after login

Example of a Recursive Repeat Macro

Using these techniques, we can create a recursive REPEAT macro:

#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
EVAL(REPEAT(8, M, ~)) // 0 1 2 3 4 5 6 7
Copy after login

Applicability and Limitations

While these workarounds enable recursive macros, it's important to note that they can be complex and may not work in all cases. It's recommended to approach recursive macro usage with caution and consider alternatives such as functions or template metaprogramming when appropriate.

The above is the detailed content of Can We Create Recursive Macros in C/C Preprocessing?. 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