C variable length parameters
What is variable length parameters
Variable length parameters is for function like printf(). The length of parameters is not fixed for printf(). We can pass in as many parameters as we want.
For example,
sum();
sum(1);
sum(1,2);
sum(1,2,3);
The sum function just adds all parameters together.
Functions to use
type va_arg(va_list argptr, type);
void va_copy(va_list target, va_list source);
void va_end(va_list argptr);
void va_start(va_list argptr, last_parm);
We use va_arg(), va_start(), and va_end() to deal with a variable number of arguments to a function.
Example - Sum variable length parameters
#include <stdio.h>
#include <stdarg.h>
/*w w w . j a v a 2 s . c o m*/
double sum_series(int num, ...);
/* Variable length argument example - sum a series. */
int main(void)
{
double d;
d = sum_series(5, 0.5, 0.25, 0.125, 0.0625, 0.03125);
printf("Sum of series is %f.\n", d);
return 0;
}
double sum_series(int num, ...)
{
double sum=0.0, t;
va_list argptr;
/* initialize argptr */
va_start(argptr, num);
/* sum the series */
for( ; num; num--) {
t = va_arg(argptr, double); /* get next argument */
sum += t;
}
/* do orderly shutdown */
va_end(argptr);
return sum;
}
The code above generates the following result.
Example - Calculating an average using variable argument lists
#include <stdio.h>
#include <stdarg.h>
//from w w w .jav a 2 s. com
double average(double v1 , double v2,...);
int main()
{
printf("\n Average = %lf", average(3.5, 4.5, 0.0));
printf("\n Average = %lf", average(1.0, 2.0));
printf("\n Average = %lf\n", average(0.0,1.2,1.5));
}
double average( double v1, double v2,...)
{
va_list parg;
double sum = v1+v2;
double value = 0;
int count = 2;
va_start(parg,v2);
while((value = va_arg(parg, double)) != 0.0)
{
sum += value;
printf("\n in averge = %.2lf", value);
count++;
}
va_end(parg); /* End variable argument process */
return sum/count;
}