I was looking for a way to pass an indefinite number of arguments to a function when I came across the way to do this using va_list
, va_start
and va_end
of stdarg.h as illustrated in the program given here.
But couldn't find anywhere a way to access the indefinite number of arguments passed to function in a random fashion.
The way using va_list
from stdarg.h header file is accessing the arguments sequentially. Once one argument is read there is no going back.
Is there a way to randomly access these arguments?
EDIT: I was advised to post the code instead of a link to the page containing it. So here it is:
#include <stdarg.h>
#include <stdio.h>
/* this function will take the number of values to average
followed by all of the numbers to average */
double average ( int num, ... )
{
va_list arguments;
double sum = 0;
/* Initializing arguments to store all values after num */
va_start ( arguments, num );
for ( int x = 0; x < num; x++ )
{
sum += va_arg ( arguments, double );
}
va_end ( arguments ); // Cleans up the list
return sum / num;
}
int main()
{
printf( "%f\n", average ( 3, 12.2, 22.3, 4.5 ) );
/* here it computes the average of the 5 values 3.3, 2.2, 1.1, 5.5 and 3.3
printf( "%f\n", average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ) );
}