0

I have a function with some variable arguments params, and I need to call inside it another function passing this arguments. For example, someone call this function:

bool A(const char* format, ...)
{
  //some work here...
  bool res = B(format, /*other params*/);
  return res;
}

bool B(const char* format, /**/, ...)
{
   va_list arg;
   va_start(arg, format);
   //other work here...
}

I need to know, how to pass the variable params by the ellipse received by A to B function. Thanks

yosbel
  • 1,711
  • 4
  • 20
  • 32

3 Answers3

4

You cannot do that directly, so you need to follow the same pattern that C library follows with fprintf / vfprintf groups of functions.

The idea is to put the implementation into the v-prefixed function, and use the user-facing function with no v prefix to "unwrap" the va_list before calling the real implementation.

bool A(const char* format, ...)
{
  //some work here...
   va_list arg;
   va_start(arg, format);
   bool res = vB(format, arg);
   va_end(arg);
   return res;
}

bool B(const char* format, /**/, ...)
{
   va_list arg;
   va_start(arg, format);
   bool res = vB(format, arg);
   va_end(arg);
   return res;
}

bool vB(const char* format, va_list arg) {
    // real work here...
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

It is not possible to pass them in the usual notation the only thing that is possible is to forward variable arguments to a function that accepts a va_list. Example for forwarding arguments to vprintf (the va_list version of printf):

int printf(const char * restrict format, ...) {
  va_list arg;
  va_start(arg, format);
  int ret = vprintf(format, arg);
  va_end(args);
  return ret;
}
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
2

There you go:

bool A(const char* format,...)
{
    bool res;
    va_list args;
    va_start(args,format);
    res = B(format,args);
    va_end(args);
    return res;
}
barak manos
  • 29,648
  • 10
  • 62
  • 114
  • 1
    in that case, `B()` must be `bool B( const char *, va_list );` instead of `bool B( const char *, ... );` – Ingo Leonhardt Apr 29 '14 at 17:23
  • @Ingo Leonhardt: So according to what you're saying, `printf` also takes `const char *, va_list` instead of `const char *, ...`, which is not correct to the best of my knowledge. Are you sure about this? – barak manos Apr 29 '14 at 17:26
  • 2
    yout couldn't (portably) call `printf()` like that, but you had to use `vprintf()` instead, which indeed is `int vprintf( const char *, va_list );`. Look at @Sergey L.'s answer – Ingo Leonhardt Apr 29 '14 at 17:29