Vink
Vink

Reputation: 1039

forwarding parameters from variadic function to fixed argument function

I have a function which takes a variable number of arguments. From this function I want to call functions that take fixed number of arguments,

void log(int level, const char* format, ...)
{
    va_list args;
    va_start(args, fmt);

    int count = 0;
    void *navigator[10] = NULL;

    while ((navigator[count] = va_arg(args, char*) ) != NULL && count < 10) 
        ++count;   //Is this the right way to count no. of arguments passed ?


    fprintf(stderr, "**** No of arguments : %d\n", count);
    fflush(stderr);

    switch (count - 2)
    {
    case 0:
                log_l(level, fmt);
        break;
    case 1:
           log_l1(level, fmt, navigator[0]);  // how would I get arg1 here, 
                                              // I get NULL in the called function)*/
        break;
         .
         .
         .
         .
         .

    };
}

I want to know the right way of counting the number of parameters passed and then properly forward them to other fixed parameter functions.

Upvotes: 0

Views: 367

Answers (2)

Mark B
Mark B

Reputation: 96241

Your va_start needs to be va_start(args, format); // Note change to "format".

EDIT: Even with this according to the manpage fro va_arg you can't do what you want.

If there is no actual next argument, or iftype is not compatible with the type of the actual next argument (as promoted according to the default argument pro- motions), the behavior is undefined.

But this is tagged C++ so why not use the C++ idiom: Use streams and an insertion operator<< instead of using varargs at all.

Upvotes: 1

Erik
Erik

Reputation: 91270

There is no way - you need to pass this information explicitly, e.g. with a count parameter or an explicit 0 as last parameter. Type info isn't passed in any form either.

Upvotes: 1

Related Questions