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);
}
3
  • 1
    Do not use variable number of arguments. It is a silly idea and not type safe Commented Dec 8, 2013 at 16:35
  • 2
    Why do you want to make spaghetti? Commented Dec 8, 2013 at 16:35
  • You might want to look up variadic templates. They'll at least let you do this a little more cleanly (e.g., without destroying type-safety). Commented Dec 8, 2013 at 16:36

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.