C - Variable Arguments

Use stdarg.h to write functions that accept a variable number of arguments.

Example

#include <stdio.h>
#include <stdarg.h>

int sum(int count, ...) {
  va_list ap; va_start(ap, count);
  int total = 0;
  for (int i = 0; i < count; i++) total += va_arg(ap, int);
  va_end(ap);
  return total;
}

int main(void) {
  printf("%d\n", sum(4, 1, 2, 3, 4)); // 10
}

Common Pitfalls

  • Forgetting to call va_end.
  • Type mismatches: the callee must know the types of variable args.