Using variable argument functions dynamically

1.1k views Asked by At

I've been looking for the answer but i'm not sure, do variable argument functions get created or resolved at compile time or dynamically? For example , is it ok to take user's input at run-time and then call the function according to how many inputs were entered? Thanks

void func(int num_args, ...)
{
 ....
}
3

There are 3 answers

3
TartanLlama On

The number and types of function arguments are resolved at compile time, the values are resolved at compile-time or run-time depending on whether their value is constexpr-like or not.

Think about how you would call a function with an arbitrary number of variables collected at runtime. There is no C++ syntax for such a construct.

What you should do instead is use something like std::vector. An example with some dummy functions:

void func (const std::vector<std::string>& args);
std::string getarg();
bool haveargs();

int main() {
    std::vector<std::string> args;
    while (haveargs()) {
        args.push_back(getarg());
    }
    func(args);
}
0
Evil Dog Pie On

They are created at compile time. Rather then passing a list of discrete parameters, you use the va_start macro to get a stack address wrapped in the returned va_list structure. The va_start macro uses the last defined argument passed to the function, so it is usual to use this to provide a mechanism to determine the actual, run time number of arguments as well as their types. For example, printf requires a format string as the other arguments may be different sizes, whereas the code below uses a simple count as it expects only integers.

int average(int count, ...)
{
    va_list valist;
    int total;
    int i;

    // Initialize valist for number of arguments specified by count.
    va_start(valist, count);

    // Get the total of the variable arguments in the va_list.
    for(total = 0, i = 0; i < num; i++)
    {
        // Use va_arg to access the next element in the va_list
        // by passing the list and the type of the next argument.
        total += va_arg(valist, int);
    }

    // Release the va_list memory.
    va_end(valist);

    return total/count;
}

// Using the function: pass the number of arguments
// then the arguments themselves.
printf("The average is %d.", average(3, 1, 2, 3));

Output: The average is 2.
0
RamblingMad On

do variable argument functions get created or resolved at compile time or dynamically?

C++ is not a JIT compiled language (usually), so run-time function creation isn't possible at the language level.


is it okay to take user's input at run-time and then call the function according to how many inputs were entered?

Of course, but make sure you do error checking!


All in all I would recommend against using C-style variadic functions and instead split it up into a different function for each individual argument type. Variadic functions are fraught with danger and easy to mess up.