Poornima M
Poornima M

Reputation: 1

Passing a variable set of arguments from one function to a macro in C

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...
}

Upvotes: 0

Views: 725

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 57922

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().

Upvotes: 1

Related Questions