0

I see this link Passing variable arguments to another function that accepts a variable argument list. What is the syntax to pass it to a macro as well?

#include <stdarg.h>
#define exampleW(int b, args...) function2(b, va_args)
static void exampleV(int b, va_list args);

void exampleB(int b, ...)
{
    va_list args;
    va_start(args, b);
    exampleV(b, args);
    //also pass args to a macro which takes multiple args after this step
    ??? [Is it exampleW(b, ##args)]
    va_end(args);
}

static void exampleV(int b, va_list args)
{
    ...whatever you planned to have exampleB do...
    ...except it calls neither va_start nor va_end...
}
  • A macro takes pieces of source code and manipulates them when you compile. A `va_list` represents values like numbers and pointers and helps access them when the program is running. You seem to want something that mixes those categories and uses them out of the only order they happen. – aschepler May 29 '20 at 03:09
  • Do you mean this `#define function(...) function2( __VA_ARGS__ )` ? – isrnick May 29 '20 at 03:41
  • To make my question clear, I need to pass a set of variable arguments from one function(which itself has got the variable args as input) to a macro called inside. – Poornima M May 29 '20 at 04:32

1 Answers1

1

This is not possible. Macros are expanded at compile time, and so their arguments need to be known at compile time, at the point where the macro is used. The arguments to your function exampleB are in general not known until run time. And even though in many cases the arguments may be known when the call to the function is compiled, that may be in a different source file, which does not help you with macros in this source file.

You'll need to either:

  • have exampleB instead call a function like vfunction2 which is function2 rewritten to take a va_list parameter

  • reimplement exampleB as a macro

  • if there are a finite number of possible combinations of arguments to exampleB, then write code to handle all the cases separately:

if (b == TWO_INTS) {
    int i1 = va_arg(args, int);
    int i2 = va_arg(args, int);
    exampleW(i1, i2);
} else if (b == STRING_AND_DOUBLE) {
    char *s = va_arg(args, char *);
    double d = va_arg(args, double);
    exampleW(s,d);
} else // ...
  • do something non-portable to call the function function2 with the same arguments as were passed to exampleB, e.g. with assembly language tricks, or gcc's __builtin_apply().
Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82