I have an inline variadic function
inline int foo(...)
I need foo()
to call a macro (let's call it MACRO
), which is also variadic.
Basically I need foo()
to pass all its input parameters to MACRO
. Redefining foo()
as another macro would be an easy solution because of __VA_ARGS__
option, but I also need foo()
to return a value.
Note: I am trying to interface two parts of already written code and I am not allowed to change them. foo(...)
is used in the first part of code and MACRO
is defined in the second part. Only thing I am supposed to do is to define a foo()
which uses MACRO
and I can't because they are both variadic.
Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.
To use variadic macros, the ellipsis may be specified as the final formal argument in a macro definition, and the replacement identifier __VA_ARGS__ may be used in the definition to insert the extra arguments. __VA_ARGS__ is replaced by all of the arguments that match the ellipsis, including commas between them.
To access variadic arguments, we must include the <stdarg. h> header.
The variable argument is completely macro-expanded before it is inserted into the macro expansion, just like an ordinary argument. You may use the ' # ' and ' ## ' operators to stringize the variable argument or to paste its leading or trailing token with another token.
Make foo
a macro that contains a lambda that returns a value, and then invokes that lambda.
#define foo(...) \
[&](auto&&...args){ \
/* do something with args, or __VA_ARGS__ */ \
MACRO(__VA_ARGS__); \
return 7; \
}(__VA_ARGS__)
now int x = foo(a, b, c);
will both call the lambda inside foo
, and inside that lambda call the macro on (a, b, c)
, and can return a value.
I pity whomever maintains your code next.
What you're asking is impossible.
A variadic function's arguments are determined at runtime, but a macro expands at compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With