kesari kesari - 4 years ago 104
C Question

Dynamic function calls

How do you write a runtime-dynamic function call in C which would take a variable number of arguments during runtime?

For example, consider

long sum(int count, ...);
, which returns the sum of the values of the (integer) arguments passed to it.

$./a.out 1 2 3 4

10

$./a.out 1 2 3 4 -5

5

Answer Source

You just can't. Alas, you only can call a variadic function with a given number of arguments, but not with an array.

Depending on the architecture, you can call the function "behind" the variadic one - the one which takes a va_list, provided there is one, such as vprintf() "behind" printf() - with the array's address, but that would be highly unportable. Better don't do this.

The best would be to create a 3rd function, such as:

long asum(int count, long * arr)
{
    long s = 0;
    for (int i=0; i < count, i++) {
        s += arr[i];
    }
    return s;
}

long vsum(int count, va_list ap)
{
    long s = 0;
    for (int i=0; i < count, i++) {
        s += va_arg(ap, long);
    }
    return s;
}

long sum(int count, ...)
{
    va_list ap;
    va_start(ap, count);
    long ret = vsum(count, ap);
    va_end(ap);
    return ret;
}

This asum() would be the one you'd call. But this only works with an intermediate array which you convert the command line arguments to.

Maybe an additional ssum() would help:

long ssum(int count, char ** arr)
{
    long s = 0;
    for (int i=0; i < count, i++) {
        s += atol(arr[i]); // I am not sure if this is very portable; if not, choose another way.
    }
    return s;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download