The best C variable parameter Tutorial In 2024, In this tutorial you can learn C variable parameter
Sometimes you may encounter such a situation, you want to function with variable number of arguments, rather than a predefined number of arguments. C language for this scenario provides a solution that allows you to define a function that can accept a variable number of parameters according to specific needs. The following example demonstrates the definition of such a function.
int func(int, /en. ) { . . . } int main() { func(1, 2, 3); func(1, 2, 3, 4); }
Please note that the functionfunc () a final written arguments ellipsis that three dots (/en.),that argument before the ellipsis is alwaysint,representing the total number of variable parameters to be passed. To use this feature, you need to usestdarg.h header file that provides the functionality of variable parameters to achieve functions and macros.Specific steps are as follows:
Let us now follow the steps above to write functions with a variable number of arguments and returns their average:
#include <stdio.h> #include <stdarg.h> double average(int num,/en.) { 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 is compiled and executed, it produces the following result. It should be noted that the functionaverage () is called twice, each time the first parameter represents the total number are transferred variable parameters.Ellipses are used to deliver a variable number of arguments.
Average of 2, 3, 4, 5 = 3.500000 Average of 5, 10, 15 = 10.000000