How to loop through a va_list if the number of arguments is unknown?

后端 未结 5 629
遇见更好的自我
遇见更好的自我 2021-02-13 14:57

How do I loop through a va_list if the number of additional arguments is unknown?

#include 
#include 

int add(int x, int y, ...         


        
5条回答
  •  星月不相逢
    2021-02-13 16:04

    You use the first argument to indicate the number of elements, and then, you can pass any number of elements to the function.

    Here is a typical call:

    int i = add(5, 20, 30, 40, 50, 60);
    

    There are 5 numbers to sum, so the first parameter is 5. Then the rest are the 5 numbers to add up.

    The function would then be:

    int add(int argc, ...)
    {
        int result = 0;
        va_list ptr;
        va_start(ptr, argc);
    
        for (int i = 0; i < argc; i++)
        {
            result += va_arg(ptr, int);
        }
        return result;
    }
    

    References:

    va_arg()

    va_start()

    va_list()

提交回复
热议问题