C++ Standard Library C++ STL Library

C++ <cstdarg> - va_start



The C++ <cstdarg> 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 reference type or with a type not compatible with the type that results from default argument promotions, the behavior is undefined.

Return Value

None.

Example:

The example below shows the usage of va_start macro function.

#include <iostream>
#include <cstdarg>

using namespace std;

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 () {
  cout<<"Sum is: "<<add_nums (2, 10, 20)<<"\n";
  cout<<"Sum is: "<<add_nums (3, 10, 20, 30)<<"\n";
  cout<<"Sum is: "<<add_nums (4, 10, 20, 30, 40)<<"\n";
  return 0;
}

The output of the above code will be:

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

❮ C++ <cstdarg> Library