Using an explicit count argument to determine the length of the va list

suggest change

With any variadic function, the function must know how to interpret the variable arguments list. With the printf() or scanf() functions, the format string tells the function what to expect.

The simplest technique is to pass an explicit count of the other arguments, which are normally all the same type. The function below sums that many int arguments. n must be nonnegative and equal to the number of int arguments that follow. A larger count makes va_arg read past the arguments, which is undefined behavior.

#include <stdio.h>
#include <stdarg.h>

/* first arg is the number of following int args to sum. */
int sum(int n, ...) {
    int sum = 0;
    va_list it; /* hold information about the variadic argument list. */

    va_start(it, n); /* start variadic argument processing */
    while (n--)
      sum += va_arg(it, int); /* get and sum the next variadic argument */
    va_end(it); /* end variadic argument processing */

    return sum;
}

int main(void)
{
    printf("%d\n", sum(5, 1, 2, 3, 4, 5)); /* prints 15 */
    printf("%d\n", sum(10, 5, 9, 2, 5, 111, 6666, 42, 1, 43, -6218)); /* prints 666 */
    return 0;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents