Example 1 — Sum a variable number of integers
The first argument says how many values follow.
#include <stdio.h>
#include <stdarg.h>
int sum(int count, ...) {
va_list ap;
int total = 0;
va_start(ap, count);
for (int i = 0; i < count; i++) {
total += va_arg(ap, int);
}
va_end(ap);
return total;
}
int main(void) {
printf("sum(3, 10, 20, 30) = %d\n", sum(3, 10, 20, 30));
printf("sum(5, 1, 2, 3, 4, 5) = %d\n", sum(5, 1, 2, 3, 4, 5));
return 0;
} How It Works
va_startinitializes the list after the last named parameter.- Each
va_arg(ap, int)fetches the next argument. va_endcleans up before returning.
