C Standard Library

C <stdarg.h> - va_list Type



The C <stdarg.h> va_list type is used to hold information about variable arguments. It is suitable for holding the information needed by the macros va_start, va_copy, va_arg, and va_end.

va_start initializes an object of this type in such a way that subsequent calls to va_arg sequentially retrieve the additional arguments passed to the function.

Before a function that has initialized a va_list object with va_start returns, the va_end macro shall be invoked.

It is legal to pass a pointer to a va_list object to another function and then use that object after the function returns.

In the <stdarg.h> header file, it is defined as follows:

typedef /* unspecified */ va_list;              

Example:

The example below shows the usage of va_list type.

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

int add_nums(int count, ...) {
  int result = 0;
  va_list args;

  va_start(args, count);
  for (int i = 0; i < count; ++i) {
    result += va_arg(args, int);
  }
  va_end(args);
  return result;
}

int main () {
  printf("Sum is: %d\n", add_nums (2, 10, 20));
  printf("Sum is: %d\n", add_nums (3, 10, 20, 30));
  printf("Sum is: %d\n", add_nums (4, 10, 20, 30, 40));
  return 0;
}

The output of the above code will be:

Sum is: 30
Sum is: 60
Sum is: 100

❮ C <stdarg.h> Library