Question

I have a function which accepts variable number of argumets of different data types using ellipsis. I wanted to know is there any way by which I can get each of them. If not all, atleast separate a particular argument (either first or last parameter) from the rest and va_list from the remaining.
Declaration goes like this :

    int foo (char *a , ...)

Usage :

    result = foo ("I'm a String",2,34.56,"one more String",2323232323);

    result = foo ("I'm another String",3,"again one more String",34.62,111111111);

So, here(usage 1) I want to remove parameter '2' from the va_list got and make another va_list with the rest. Function declaration is flexible, and can be changed accordingly.
Thanks in advance

Was it helpful?

Solution

Note that variable argument functions must have a way to determine the types of the arguments in the ellipsis (va_list). The printf() and scanf() families of functions have the format string to specify the types; the open() system call has an optional third argument but it is always an int; and the execl() function takes a list of arguments all of the same type, char *, terminated by a NULL pointer).

If you have a function:

void foo_tail(va_list args);

You can write your function foo() as:

int foo(char *a, ...)
{
    va_list args;
    va_start(args, a);
    int arg2 = va_arg(args, int);
    foo_tail(args);
    va_end(args);
    return arg2;
}

This achieves what the question asks for:

remove parameter '2' from the va_list got and make another va_list with the rest.

Whether foo_tail() can work out what to do with the va_list it is given is a separate discussion; it is not clear how it would distinguish between the two calls shown in the question, but to handle both, that information would have to be made available somehow. A variable list of mixed types as shown is very problematic.

OTHER TIPS

When you use va_arg the argument you get is actually removed from the va_list. So the rest of the arguments are already in your va_list.

However, you can not, say, get an arbitrary argument from the list. They have to be taken in order. You also must know the actual types of the arguments you're getting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top