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

0

3 Answers 3

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...
}
Sign up to request clarification or add additional context in comments.

3 Comments

GCC has an extension doing that though.
@Deduplicator It is best to program to the language free of extensions for maximum portability.
I concurr, just mentioning it for completeness.
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;
}

1 Comment

So, there is not possible way, just doing another function...
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;
}

3 Comments

in that case, B() must be bool B( const char *, va_list ); instead of bool B( const char *, ... );
@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?
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.