Variable Arity in C?

后端 未结 4 968
借酒劲吻你
借酒劲吻你 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:15

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

    #include 
    
    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).

提交回复
热议问题