capypad
0 day streak
c / intermediate
Snippet

Variadic Functions using stdarg.h

Variadic functions allow you to pass a variable number of arguments to a function. This is achieved using the macros defined in <stdarg.h>. You must provide at least one fixed argument (like 'count') to know where the variable list starts.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
#include <stdarg.h>
 
void print_log(int count, ...) {
va_list args;
va_start(args, count);
for (int i = 0; i < count; i++) {
printf("%s ", va_arg(args, char*));
}
va_end(args);
}
Breakdown
1
va_list args;
Declares a variable to hold the information needed by the macros.
2
va_arg(args, char*)
Retrieves the next argument from the list, interpreted as the specified type (char*).