C Language | Advanced Features | Variadic Arguments

Variadic functions accept a variable number of arguments, as printf() does.

Ellipsis and Variadic Arguments

Write an ellipsis (...) after the final fixed parameter.

int printf(const char *format, ...);

Use the macros declared in stdarg.h to access the arguments:

void va_start(va_list arg_ptr, prev_param);
type va_arg(va_list arg_ptr, type);
void va_end(va_list arg_ptr);

va_start() initializes a va_list. Its second argument is the final fixed parameter. Each call to va_arg() retrieves the next argument as the specified type. Call va_end() when finished.

The function must know the number and types of the arguments. printf() derives that information from its format string. Default argument promotions also apply: retrieve a floating-point variadic argument as double, not float.

fValue = va_arg(arg_ptr, double);
pStr = va_arg(arg_ptr, char *);

Code 1

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

void DynamicParameter(int arg_num, ...) {
  va_list args;
  int iValue, iCount;

  if (arg_num < 1) return;
  va_start(args, arg_num);
  for (iCount = 0; iCount < arg_num; iCount++) {
    iValue = va_arg(args, int);
    printf("argument %d = %d\n", iCount + 2, iValue);
  }
  va_end(args);
}

int main() {
  DynamicParameter(4, 10, 20, 30, 40);
  return 0;
}

This function receives the number of optional arguments first, then reads that many int values. Variadic functions can be flexible, but parsing arguments adds complexity and should be used only when appropriate.