C++ Standard Library C++ STL Library

C++ <cstdarg> - va_list Type



The C++ <cstdarg> 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 <cstdarg> header file, it is defined as follows:

typedef /* unspecified */ va_list;              

Example:

The example below shows the usage of va_list type.

#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