/* Example of a variadic function in C, taken directly from Wikipedia https://en.wikipedia.org/wiki/Variadic_function Also, according to Wikipedia: stdarg.h declares a type, va_list, and defines four macros: va_start, va_arg, va_copy, and va_end. Each invocation of va_start and va_copy must be matched by a corresponding invocation of va_end. When working with variable arguments, a function normally declares a variable of type va_list (ap in the example) that will be manipulated by the macros. */ #include #include double average(int count, ...) { va_list ap; // variable that will contain the list of arguments. double sum = 0; va_start(ap, count); // this isn't providing the length of the list, it is letting the compiler know what parameter the ellipses follow. for (int j = 0; j < count; ++j) { sum += va_arg(ap, int); /* Increments ap to the next argument. */ } va_end(ap); // Clean-up return sum / count; } int STOP_ITEM = -1; // Demo the variable arguments where we use a sentinel value to indicate we are at the // last time of the list. double average_sentinel(char *name, ...) { va_list ap; // variable that will contain the list of arguments. double sum = 0; int count = 0; va_start(ap, name); // this isn't providing the length of the list, it is letting the compiler know what parameter the ellipsis follow. We aren't using the name for anything but my compiler is old enough that it requires a parameter before the ellipsis. int item = va_arg(ap, int); // get the first item as an int, then go to next argument. while (item != STOP_ITEM) { sum += item; count++; item = va_arg(ap, int); /* Increments ap to the next argument. */ } va_end(ap); // Clean-up return sum / count; } int main(int argc, char* argv[]) { printf("%f\n", average(3, 1, 2, 3)); printf("%f\n", average_sentinel("hi", 1, 2, 3, -1)); return 0; }