C
stdarg.h
Learn variadic functions with stdarg.h.
stdarg.h
In C some functions take a variable number of arguments: printf for example. The <stdarg.h> header provides tools that make this easy.
There are four core pieces: va_list (the argument list type), va_start(list, last_fixed) (initializes the list), va_arg(list, type) (reads the next argument), va_end(list) (closes the list). The key point: the function must somehow know how many arguments it received. printf derives this from the format string; a function like sum_n takes the count as its first argument. The ... ellipsis at the end of the signature marks where variable arguments begin.
The sum_n example
Let's write a variadic function: int sum_n(int count, ...). The first parameter count tells how many numbers to add; the ... represents the numbers themselves.
Definition: va_list args; va_start(args, count); int total = 0; for (int i = 0; i < count; i++) total += va_arg(args, int); va_end(args); return total;. The second argument to va_start is the last fixed parameter; here count. This tells the compiler where the variable arguments begin in memory. Each call to va_arg advances to the next argument and reads it as the given type. When the loop ends, va_end closes the list. Call: sum_n(3, 10, 20, 30) → 60.
Exercise The sum_n function
Write int sum_n(int count, ...). Inside: va_list args;, va_start(args, count);, in a for loop total += va_arg(args, int);, after the loop va_end(args);, return total;. In main call printf("%d\n", sum_n(3, 10, 20, 30));.
Show example solution
#include <stdio.h>
#include <stdarg.h>
int sum_n(int count, ...) {
va_list args;
va_start(args, count);
int total = 0;
for (int i = 0; i < count; i++) {
total += va_arg(args, int);
}
va_end(args);
return total;
}
int main(void) {
printf("%d\n", sum_n(3, 10, 20, 30));
return 0;
}
Test yourself
-
What does va_arg do?
- reads the next argument
- starts the list
- ends the list
- returns the argument count
Show answer
reads the next argument — va_arg(list, type) reads the next argument.
-
stdarg macros
- va_list
- argument list type
- va_start
- start the list
- va_arg
- read next
- va_end
- close the list
-
The va_start call
va_start(args, ____);
Show answer
va_start(args, count);
Next lesson: va_start and va_end