The variable parameter list is implemented through macros, which are defined in the stdarg.h header file. The execution steps are as follows:
- The ellipsis in the parameter list means that the number and type of parameters that may be passed here are not determined
- First, declare a variable value of type va_list in the function , which is used to access the undetermined part of the parameter list . This variable is a pointer to the parameter
- Use the macro va_start to initialize the defined variable of type va_list. The first parameter of the macro va_start is the name of the va_list variable value, and the second parameter is the last named parameter before the ellipsis . The initialization process points the variable value of the va_list type to the variable The first parameter of the parameter section
- Use the macro va_arg to return a variable parameter . The macro va_arg receives two parameters: a variable of type va_list and the type of the next parameter in the parameter list, and makes value point to the next variable parameter.
- After accessing the last variable parameter, use the macro va_end to end the acquisition of the variable parameter
Note : Variable parameter access must be accessed one by one in order from beginning to end
/*求n个整形参数的平均值,利用可变参数列表来实现
形参列表中必须要有一个固定值,不能只有省略号所代表的未确定参数*/
#include <stdio.h>
#include <stdarg.h>
float average(int n_values,...)
{
va_list value; //va_list类型声明
int count;
float sum=0;
float average;
/*准备访问可变参数*/
va_start(value,n_values); //初始化参数,指向第一个可变参数
/*添加取自可变参数列表的值*/
for(count=0;count<n_values;count++)
{
sum += va_arg(value,int); //取当前参数,并指向下一个参数
}
va_end(value); //完成可变参数的处理
average=((float)((int)((sum/values+0.005)*100)))/100; //取小数点后两位,四舍五入
return average;
}
#define n_values 3
int main()
{
float aver;
aver=average(n_values,9,9,8);
printf("%.2f",aver); //保留两位小数打印
return 0;
}