#include<stdio.h>
#include<Windows.h>
#include<stdarg.h> //Variable parameter lists are implemented through macros, which are defined in the stdarg.h header file
int average( int n, ...)//... is the variable parameter list part
{
va_list arg;//Declare a variable arg of type va_list
int i = 0;
int max = 0;
va_start(arg, n);//va_start to initialize arg, arg points to the first element of the variable parameter
for (i = 0; i < n; i++)
{
int val = va_arg(arg, int);//The int type is used as a parameter, the purpose is to read the int length value, va_arg is a macro;
if (max < val)
{
max = val;
}
}
return max;
va_end(arg);//When accessing the last variable parameter, you need to call va_end to clean up the parameter list;
}
int main()
{
int a = 13;
int b = 22;
int c = 12;
int num1 = average(3, a, b, c);//When using variable parameters, you should first enter the number of variable parameters, and then pass in the parameters.
printf("%d ", num1);
system("pause");
return 0;
}
1) Declare a variable arg of type va_list, arg is a pointer to the first parameter, used to access the undetermined part of the parameter list
2) Then initialize the variable arg with the va_start macro, the second parameter of this macro is ' The last named parameter before ...'.
3) Use va_arg to access the variable parameter and assign it to val. The second parameter of va_arg is the type of the parameter to be read, which is int here. At the same time va-arg points to the next variadic parameter
4) Use end, end the variadic parameter with the va_end macro.
About stdarg macros
Variable argument lists are implemented through macros, which are defined in the stdarg.h file. This file declares a type va-list and three macros va-start, va-arg, va-end. The role of the three macros is only to determine the memory address of each parameter in the variable parameter list. The compiler does not Know the actual number of parameters. The "..." in the parameter is used to indicate that an undetermined number and type of parameters may be passed here.
variadic parameters ①Variable parameters must be accessed one by one from the beginning to the end, and can be stopped in the middle.
②If you want to access the intermediate elements from the beginning, it is not acceptable