简体   繁体   中英

Variable Arity in C?

Does anyone knows how I might be able to implement variable arity for functions in C?

For example, a summing function:

Sum(1,2,3,4...); (Takes in a variable number of args)

Thanks!

A variable parameter list of ints. Adjust type as necessary:

#include <stdarg.h>

void myfunc(int firstarg, ...)
{
    va_list v;
    int i = firstarg;

    va_start(v, firstarg);
    while(i != -1)
    {
        // do things
        i = va_arg(v, int);
    }

    va_end(v);
}

You must be able to determine when to stop reading the variable args. This is done with a terminator argument (-1 in my example), or by knowing the expected number of args from some other source (for example, by examining a formatting string as in printf).

If all aditional arguments are of the same type, you could also pass an array instead of using variadic macros.

With C99 compound literals and some macro magic, this can look quite nice:

#include <stdio.h>

#define sum(...) \
    sum_(sizeof ((int []){ __VA_ARGS__ }) / sizeof (int), (int []){ __VA_ARGS__ })

int sum_(size_t count, int values[])
{
    int s = 0;
    while(count--) s += values[count];
    return s;
}

int main(void)
{
    printf("%i", sum(1, 2, 3));
}

看看va_arg和朋友们

如果您正在尝试实现可变的arity函数, 参阅http://www.cprogramming.com/tutorial/lesson17.html以获取介绍。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM