# Need explanation of variable arg lists

• 05-04-2008
Countfog
Need explanation of variable arg lists
I'm reading the section of my book on Variable Length argument list functions, and I can't quite understand, how the following program averages the numbers. An average is to add the values and to divide by the number of values you added.

Where exactly does function double average( int i, ... ) do this, and how? Please explain.

Code:

#include <stdio.h>
#include <stdarg.h>

double average( int i, ... ); /* prototype */

int main()
{
double w = 37.5;
double x = 22.5;
double y = 1.7;
double z = 10.2;

printf( "%s%.1f\n%s%.1f\n%s%.1f\n%s%.1f\n\n",
"w = ", w, "x = ", x, "y = ", y, "z = ", z );
printf( "%s%.3f\n%s%.3f\n%s%.3f\n",
"The average of w and x is ", average( 2, w, x ),
"The average of w, x, and y is ", average( 3, w, x, y ),
"The average of w, x, y, and z is ",
average( 4, w, x, y, z ) );

return 0; /* indicates successful termination */

} /* end main */

/* calculate average */
double average( int i, ... )
{
double total = 0; /* initialize total */
int j; /* counter for selecting arguments  */
va_list ap; /* stores information needed by va_start and va_end */

va_start( ap, i ); /* initializes the va_list object */

/* process variable length argument list */
for ( j = 1; j <= i; j++ ) {
total += va_arg( ap, double );
} /* end for */

va_end( ap ); /* clean up variable-length argument list */

} /* end function average */

• 05-04-2008
root4
A variadic function is similar to a standard function except the compiler doesn't know
the number of its argument at compile-time. Instead you have to either indicate manually
the number of arguments (as this is done with the average() function, through i) or by
other indirect means (cf printf() and %... sequences).

Concerning the average() function you're speaking of, the code simply extracts each
argument and sum it to the previous result (starting from 0):
Code:

double total = 0; /* initialize total */
...
/* process variable length argument list */
for ( j = 1; j <= i; j++ ) {
total += va_arg( ap, double );
} /* end for */

And divide the sum by the number of arguments:
Code: