C Standard Library

C <stdarg.h> - va_start



The C <stdarg.h> va_start macro enables access to the additional arguments following the named argument parm_n.

va_start should be invoked first with the list of variable arguments as a va_list before any calls to va_arg. After the call, it carries the information needed to retrieve the additional arguments using va_arg. A function that invokes va_start, shall also invoke va_end before it returns.

Syntax

void va_start( va_list ap, parm_n );               

Parameters

ap Specify an instance of the va_list type.
parm_n Specify the named parameter preceding the first variable parameter. The arguments extracted by subsequent calls to va_arg are those after parm_n.
If this parameter is declared with register storage class, with function or array type, or with a type that is not compatible with the type that results after application of the default argument promotions, the behavior is undefined.

Return Value

None.

Example:

The example below shows the usage of va_start macro function.

#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