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

后端 未结 5 631
遇见更好的自我
遇见更好的自我 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 15:47

    The two answers above that suggest adding a first argument to indicate the number of arguments miss the point: the number of arguments is unknown.

    Using a sentinel value (or series of sentinel values) at the end is the only way to solve the problem.

    0 讨论(0)
  • 2021-02-13 15:54

    You probably want to do something like pass the number of arguments as the first parameter.

    E.g. see here: http://www.cplusplus.com/reference/clibrary/cstdarg/va_start/

    And more discussion here: http://www.learncpp.com/cpp-tutorial/714-ellipses-and-why-to-avoid-them/

    Variable arguments can be hazardous so if at all possible I'd try to avoid them. Passing a "vector" type which includes size and a pointer to the element array would be safer.

    0 讨论(0)
  • 2021-02-13 15:57

    Use a sentinel value as a terminator, e.g NULL or -1

    0 讨论(0)
  • 2021-02-13 16:00

    You must indicate the number of parameters somehow (if you're writing portable code) when using variable length argument lists. You may be now thinking "But printf doesn't require you to indicate a number of arguments!"

    True, however the number can be inferred by first parsing the format strings for % format specifiers.

    0 讨论(0)
  • 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()

    0 讨论(0)
提交回复
热议问题