C++ Standard Library C++ STL Library

C++ <cstdarg> - va_arg



The C++ <cstdarg> va_arg macro expands to an expression of type T that corresponds to the next parameter from the va_list ap.

Prior to calling va_arg, ap must be initialized by calling either va_start or va_copy, without any intervening call to va_end. Each call to this micro modifies ap to point to the next variable argument.

If the type of the next argument in ap (after promotions) is not compatible with T, the behavior is undefined, unless:

  • one type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types
  • one type is pointer to void and the other is a pointer to a character type (char, signed char, or unsigned char).

If this macro is called when there are no more arguments in ap, the behavior is undefined.

Syntax

void va_copy( va_list ap, T );              

Parameters

ap Specify an instance of the va_list type.
T Specify the type of the next parameter in ap.

Return Value

Returns the current additional argument as an expression of specified type.

Example:

The example below shows the usage of va_arg macro function.

#include <iostream>
#include <cstdarg>
#include <cmath>

using namespace std;

double stddev(int count, ...) {
  double sum = 0;
  double sum_sq = 0;
  va_list args;

  va_start(args, count);

  //calculating sum and sum of squares
  for (int i = 0; i < count; ++i) {
    double num = va_arg(args, double);
    sum += num;
    sum_sq += num*num;
  }
  va_end(args);

  //returning standard deviation
  return sqrt(sum_sq/count - (sum/count)*(sum/count));
}

int main () {
  cout<<"Std. deviation is: "<<stddev(2, 25.0, 30.0)<<"\n";
  cout<<"Std. deviation is: "<<stddev(3, 25.0, 30.0, 34.0)<<"\n";
  cout<<"Std. deviation is: "<<stddev(4, 25.0, 30.0, 34.0, 40.0)<<"\n";
  return 0;
}

The output of the above code will be:

Std. deviation is: 2.5
Std. deviation is: 3.68179
Std. deviation is: 5.49432

❮ C++ <cstdarg> Library