C Standard Library

C <stdarg.h> - va_arg



The C <stdarg.h> 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 <stdio.h>
#include <stdarg.h>
#include <math.h>

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 () {
  printf("Std. deviation is: %f\n", stddev(2, 25.0, 30.0));
  printf("Std. deviation is: %f\n", stddev(3, 25.0, 30.0, 34.0));
  printf("Std. deviation is: %f\n", stddev(4, 25.0, 30.0, 34.0, 40.0));
  return 0;
}

The output of the above code will be:

Std. deviation is: 2.500000
Std. deviation is: 3.681787
Std. deviation is: 5.494315

❮ C <stdarg.h> Library