c / intermediate
Snippet
Variadic Functions with stdarg.h
Variadic functions can accept a variable number of arguments. By using the 'stdarg.h' library, you can traverse these arguments using the va_list, va_start, va_arg, and va_end macros.
snippet.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>void printNumbers(int count, ...) {va_list args;va_start(args, count);for (int i = 0; i < count; i++) {printf("%d ", va_arg(args, int));}va_end(args);printf("\n");}int main() {printNumbers(3, 10, 20, 30);printNumbers(1, 5);return 0;}
Breakdown
1
va_list args;
Declares a variable to hold the list of arguments.
2
va_start(args, count);
Initializes the argument list, starting after the 'count' parameter.
3
va_arg(args, int)
Retrieves the next argument from the list, assuming it is of type 'int'.