There were several questions here regarding variadic macros in C. These include:
- How to make a variadic macro (variable number of arguments) which explains the basics, e.g., passing a variable number of arguments to functions such as
printf
- Is it possible to iterate over arguments in variadic macros?, which explains how to iteratively apply a macro to each of the arguments of the variadic macro.
- https://github.com/swansontec/map-macro which explains how to do so on pairs
My question is related to the iteration technique. I am interested in a macro with this generalized semantics.
ITERATE(Before, Action, Between, After, Empty, ...)
that will place Before
prior to all expansions, apply Action
to each argument, place Between
between every two consecutive applications, and will finally place the expansion of After
. Moreover, if the number of argument With such a macro, it should be possible to write
// Loop elements
#define A(x) (x)
#define Befor (
#define After )
#define Between ||
#define Empty 1
// Define an OR macro
#define OR(...) ITERATE(Before, A, Between, Empty, __VA_ARGS__)
// Use it
OR() // Expands to 1
OR(a) // Expands to ((a))
OR(a,b) // Expands to ((a)||(b))
OR(a,b,c) // Expands to to ((a)||(b)||(c))
The purpose of course is not to write an OR function. A generalized functionality could be for more intricate applications. E.g., a macro for defining classes and functions, something to print the trace, etc.
#define Befor ( #define After )
just#define A(x) ((x))
.... I see no point in "before" and "after", just place them inside yourAction
. Anyway, what have you tried?I would like to write
then write it. It is possible. If you want others to do the job for you, pay them. – KamilCuk