CKTIS / C
va_arg — read the next argument
The va_arg macro from <stdarg.h> reads the next argument in a function's ... portion and advances va_list state.
Version: C23; repository compiler flag, production runtime not attested
Syntax
#include <stdarg.h>
va_arg(ap, type)va_arg(ap, type) is a macro, not a function. It returns the next argument as an expression of type and advances ap. Initialize the list with va_start or va_copy, without a subsequent va_end.
Generally, type must match the type after default argument promotions. Read a passed float as double. Plain char promotes to int if int can represent every value of char, and to unsigned int otherwise. Use the resulting promoted type. If char promoted to unsigned int, reading a value greater than INT_MAX as int causes undefined behavior: the exception for corresponding signed and unsigned integer types applies only when the value is representable in both types. Outside the standard's exceptions, a type mismatch causes undefined behavior; reading past the end does too. The macro cannot detect the end: use an agreed protocol, such as a count.
Each va_start or va_copy requires a matching va_end in the same function. The example reads three double values; count specifies their number.
Examples
#include <stdarg.h>
#include <stdio.h>
static double sum(int count, ...)
{
va_list ap;
va_start(ap, count);
double total = 0.0;
for (int i = 0; i < count; ++i) {
total += va_arg(ap, double);
}
va_end(ap);
return total;
}
int main(void)
{
printf("%.1f\n", sum(3, 1.5, 2.0, 3.5));
return 0;
}
Result
7.0
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.