stdarg.h
- C course
- Intermediate
- Lesson 76/116
- 5 min
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.
Practice 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));.
Starter code
#include <stdio.h>
#include <stdarg.h>
// sum_n: add count ints and return
// declare va_list, init with va_start, read with va_arg, close with va_end
// main: call sum_n(3, 10, 20, 30) and print
int main(void) {
// write here
return 0;
}Sample 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;
}Expected output
60
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does va_arg do?
- reads the next argument Correct answer
- starts the list
- ends the list
- returns the argument count
Explanation: va_arg(list, type) reads the next argument.
2 stdarg macros
| Term | Meaning |
|---|---|
va_list |
argument list type |
va_start |
start the list |
va_arg |
read next |
va_end |
close the list |
3 The va_start call
va_start(args, ____);
va_start(args, count);
Explanation: va_start's second argument is the last fixed parameter.