C variable parameters
Sometimes, you may encounter a situation where you want a function to take a variable number of parameters instead of a predefined number of parameters. The C language provides a solution for this situation by allowing you to define a function that accepts a variable number of arguments depending on your specific needs. The following example demonstrates the definition of such a function.
int func(int, ... ) { . . .}int main(){ func(1, 2, 3); func(1, 2, 3, 4);}
Please note that the last parameter of the function func() is written as an ellipsis, that is, three dots (...). The parameter before the ellipsis is always int, represents the total number of variable parameters to be passed. In order to use this feature, you need to use the stdarg.h header file, which provides functions and macros that implement variadic functionality. The specific steps are as follows:
Define a function. The last parameter is an ellipsis. The parameter before the ellipsis is always int, which represents the number of parameters.
Create a va_list type variable in the function definition, which is defined in the stdarg.h header file.
Use int parameters and the va_start macro to initialize the va_list variable to a parameter list. The macro va_start is defined in the stdarg.h header file.
Use the va_arg macro and the va_list variable to access each item in the argument list.
Use the macro va_end to clean up the memory assigned to the va_list variable.
Now let us follow the above steps to write a function that takes a variable number of parameters and returns their average value:
#include <stdio.h>#include <stdarg.h>double average(int num,...){ va_list valist; double sum = 0.0; int i; /* 为 num 个参数初始化 valist */ va_start(valist, num); /* 访问所有赋给 valist 的参数 */ for (i = 0; i < num; i++) { sum += va_arg(valist, int); } /* 清理为 valist 保留的内存 */ va_end(valist); return sum/num;}int main(){ printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5)); printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));}
When the above code When compiled and executed, it produces the following results. It should be noted that the function average() is called twice, and each time the first parameter represents the total number of variable parameters passed. Ellipses are used to pass a variable number of arguments.
Average of 2, 3, 4, 5 = 3.500000Average of 5, 10, 15 = 10.000000