user3617487
user3617487

Reputation: 175

C vararg recursive function : what is the syntax?

I'm trying to make a recursive function with variable args in C, and I can't seem to pass the args when writing the recursive call.

Code:

void f(const char* s, ...) {
        va_list args;
        va_start(args, s);
        f(s,args);
        va_end(args);
    }
}

Don't mind the infinite call stack. It's not the point here, so I discarded every other aspect in the code.

Upvotes: 0

Views: 951

Answers (1)

user2371524
user2371524

Reputation:

A va_list is an implementation-defined way to access arguments of a function you don't know at compile time -- for example (depending on the architecture) a pointer somewhere in the stack frame of the function. You can't use it in place of actual arguments.

If you need to pass on variadic arguments, the typical approach is to have your implementation in a function that takes a va_list argument. The idiomatic way to name that function is to prepend a v to its name. So in the end, you have two functions:

void vf(const char* s, va_list ap) {
    // your logic ...
    vf(s, ap); // recursive call
}

// just a wrapper:    
void f(const char* s, ...) {
    va_list args;
    va_start(args, s);
    vf(s, args);
    va_end(args);
}

Note that this passes on a reference to the arguments your function was originally called with. If this is a problem for your logic, you can copy the whole argument list with the va_copy macro.

Upvotes: 5

Related Questions