Search code examples
c++variadic-functions

Passing variable arguments to another function that accepts a variable argument list


So I have 2 functions that both have similar arguments

void example(int a, int b, ...);
void exampleB(int b, ...);

Now example calls exampleB, but how can I pass along the variables in the variable argument list without modifying exampleB (as this is already used elsewhere too).


Solution

  • You can't do it directly; you have to create a function that takes a va_list:

    #include <stdarg.h>
    
    static void exampleV(int b, va_list args);
    
    void exampleA(int a, int b, ...)    // Renamed for consistency
    {
        va_list args;
        do_something(a);                // Use argument a somehow
        va_start(args, b);
        exampleV(b, args);
        va_end(args);
    }
    
    void exampleB(int b, ...)
    {
        va_list args;
        va_start(args, b);
        exampleV(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...
    }