Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro to call a function

I need a macro (or a function, but preferably a macro) that takes a function name and an unlimited number of arguments, then passes the arguments to the function. Let's say this macro is MACROFOO.

#define MACROFOO(function, ...)     /* what do I put here?? */

int foo_bar(int x, int y)
{
    // do stuff
}

int main(void)
{
    int x = 3;
    int y = 5;

    MACROFOO(foo_bar, x, y);    // calls foo_bar(x, y)
}

How could I define such a macro? I thought of doing something like:

#define MACROFOO(function, args...)     (function)(args)

but it looks like that passes ... to the function, instead of the actual arguments. What should I do?

like image 904
MD XF Avatar asked Oct 11 '25 19:10

MD XF


1 Answers

You can expand the ... of variadic macros with __VA_ARGS__.

Example:

#define MACROFOO(function, ...)  (function)(__VA_ARGS__)

MACROFOO(printf, "hello world%c", '!') 
/*^ expands to: (printf)("hello world%c", '!') */

Note: As you probably know, the parentheses prevent the function argument from being expanded as a macro (if it is a macro).

I.e.,

#define BAR(...) myprintf(__VA_ARGS__)
MACROFOO(BAR, "hello world%c", '!')

will expand to:

(BAR)("hello world%c", '!')

with the parentheses and

myprintf("hello world%c", '!')

if your remove them.

like image 79
PSkocik Avatar answered Oct 14 '25 09:10

PSkocik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!