Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic function calling a variadic macro

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.

like image 522
lulijeta Avatar asked Apr 29 '15 16:04

lulijeta


People also ask

What is variadic function in C?

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.

What is __ Va_args __ in C?

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.

How do you access Variadic arguments?

To access variadic arguments, we must include the <stdarg. h> header.

What is ## args in C?

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.


2 Answers

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.

like image 75
Yakk - Adam Nevraumont Avatar answered Oct 08 '22 17:10

Yakk - Adam Nevraumont


What you're asking is impossible.

A variadic function's arguments are determined at runtime, but a macro expands at compile time.

like image 35
orlp Avatar answered Oct 08 '22 17:10

orlp