Variable Arity in C?

后端 未结 4 949
借酒劲吻你
借酒劲吻你 2020-12-21 14:54

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

4条回答
  •  死守一世寂寞
    2020-12-21 15:19

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

提交回复
热议问题