0

I have a problem with function arguments. I have a function A which calls a function B. What do I have to write instead of ??? to archive that functionA passes all arguments to function B?

#include <iostream>
#include <stdarg.h>

void functionA(int a, ...);
void functionB(int a, ...);

int main()
{
    functionA(2, 5, 13);

    return 0;
}

void functionA(int a, ...)
{
    functionB(a, ??? );
}

void functionB(int a, ...)
{   
    va_list params;
    va_start(params, a);
    for(int i = 0; i<a; i++)
    {
        std::cout << va_arg(params, int) << std::endl;
    }
    va_end(params);
}
Felix
  • 15
  • 5

3 Answers3

1

You have to make two functions, one taking a variable number of arguments, and one taking a va_list.

void vunctionB(int a, va_list va)
{
    ...
}

void functionB(int a, ...)
{
    va_list va;
    va_start(va, a);
    functionB(a, va);
    va_end(va);
}

There might be other possible solutions as well, like using variadic templates in C++11.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

I don't think you can do it with .... If you rewrite functionB to take a va_list like vprintf does, that should work.

Ben Navetta
  • 457
  • 5
  • 8
0

You need to design two versions of your function, one with valists, and one with variable arguments:

void vfunctionA(int a, va_list ap)
{
    // real logic
}

void functionA(int a, ...)
{
    va_list ap;
    va_start(ap, a);
    vfunctionA(a, ap);
    va_end(ap);
}

// same for functionB

Now you can easily implement one function in terms of another:

double vrandom(int x, va_list ap)
{
    return vfunctionX(x, ap);
}

If you check the standard library or the Posix library, you'll find tons of examples for this, e.g. printf/vprintf, execl/execv (but not fork/vfork!).

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084