Write variable parameter functions in the C language
- 2020-05-26 09:44:57
- OfStack
Functions are provided with the ability to define mutable argument lists through the stdarg.h header file. The function that declares 1 variable parameter is similar to:
void f1(int n,...);
Where n represents the number of parameter lists and ellipsis represents the list of unknown parameters. An va_list type is provided in stdarg.h for storing parameters. A general usage process is similar:
void f1(int n,...)
{
va_list ap;
va_start(ap,n); // Initializes the parameter list
double first=va_arg(ap,double); // Take the first 1 A parameter
int second=va_arg(ap,int); // Take the first 2 A parameter
...
va_end(ap); // The cleanup
}
Look at an example of summation:
#include < stdio.h > #include < stdarg.h >
double sum( int ,
);
int main( void
)
{
double
s,t;
s
= sum( 3 , 1.1 , 2.2 , 13.3
);
t
= sum( 6 , 1.1 , 2.1 , 13.1 , 4.1 , 5.1 , 6.1
);
printf(
" return value for "
\
" sum(3,1.1,2.2,13.3): %g\n "
,s);
printf(
" return value for "
\
" sum(6,1.1,2.1,13.1,4.1,5.1,6.1): %g\n "
,t);
return 0
;
}
double sum( int lim,
)
{
va_list ap;
double total = 0
;
va_start(ap,lim);
int
i;
for (i = 0 ;i < lim;i ++
)
total
+= va_arg(ap, double
);
va_end(ap);
return
total;
}
The use of variable parameters in C is still a bit cumbersome, and not as easy as ruby and java. For example, variable parameters are defined and used in ruby:
def sum(*e)
e.inject{|sum,i| sum+=i}
end
sum(1,2,3,4,5)=>15