Question

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
Was it helpful?

Solution

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;
}

OTHER TIPS

The signature of main is

int main(int argc, char *argv[])

You can then access the arguments that are provided when the program.

Just parse those. Do the maths. Spit out the answer

Yes you can! Oh how the stack overflow is full of such nay-sayers.

Look at this library: http://www.dyncall.org

You can build up dynamic argument lists, and then execute an arbitrary function.

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