c / intermediate
Snippet
Variadic Functions with stdarg.h
Variadic functions allow a function to accept an indefinite number of arguments. The 'stdarg.h' header provides macros like 'va_start', 'va_arg', and 'va_end' to traverse the argument list safely by using a pointer-like 'va_list' object.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>#include <stdarg.h>double average(int count, ...) {va_list args;va_start(args, count);double sum = 0;for (int i = 0; i < count; i++) {sum += va_arg(args, int);}va_end(args);return sum / count;}int main() {printf("Avg: %.2f\n", average(3, 10, 20, 30));return 0;}
Breakdown
1
va_list args;
Declares a variable to hold the information needed by va_start, va_arg, and va_end.
2
va_start(args, count);
Initializes the va_list to retrieve arguments after the 'count' parameter.
3
va_arg(args, int);
Retrieves the next argument in the list, interpreted as the specified type (int).