
Patrick B. answered 06/03/19
Math and computer tutor/teacher
The caller initializes the va_list and passes it.
Specifically, the calling function does va_start( valist, x);
and then passes it to the helper function.
The helper function must CLOSE it off by doing va_end(valist);
or else you have a memory leak;
Also the helper function(s) must be declared AHEAD of the caller, or else
the compiler complains, unless you do a forward reference (or put them in a header)
Here is an example:
#include <stdio.h>
#include <stdarg.h>
double average(int num,va_list valist)
{
double sum = 0.0;
int i;
/* accesses all the arguments assigned to valist */
for (i = 0; i < num; i++)
{
sum += va_arg(valist, int); //updates running total
}
/* cleans memory reserved for valist */
va_end(valist);
return sum/num; //returns the average
}
double max(int num, va_list valist)
{
double max=0.0;
int i;
double x;
max = -32767;
for (i=0; i<num; i++)
{
x = va_arg(valist,int);
if (x>max) { max = x; }
}
va_end(valist);
return max;
}
double min(int num, va_list valist)
{
double min=0.0;
int i;
double x;
min = 32768;
for (i=0; i<num; i++)
{
x = va_arg(valist,int);
if (x<min) { min = x; }
}
va_end(valist);
return min;
}
double driver ( int opFlag, int num,...)
{
va_list valist;
double dReturn = 0;
//initializes the variable argument list
va_start(valist, num);
switch (opFlag)
{
case 1: //average
{
dReturn = average(num,valist);
break;
}
case 2: //max
{
dReturn = max(num,valist);
break;
}
case 3: //min
{
dReturn = min(num,valist);
break;
}
default:
{
printf(" say what???? \n" );
break;
}
}//switch
return(dReturn);
}
int main()
{
printf("Average of 2, 3, 4, 5 = %f\n", driver(1,4, 2,3,4,5));
printf("Average of 5, 10, 15 = %f\n", driver(1,3, 5,10,15));
printf(" max of 4,8, 6, 12, 5 = %f\n", driver(2,5,4,8,6,12,5));
printf(" min of 4,8, 6, 12, 5 = %f\n", driver(3,5,4,8,6,12,5));
printf(" max of 2 , 3, 1 = %f\n", driver(2,3,2,3,1));
printf(" min of 2, 3, 1 = %f\n", driver(3,3,2,3,1));
}