In some applications, we want the number of arguments for a parameter to be variable to meet the requirements, such as the library functions printf and scanf in stdio.h. The following example:
#include <iostream>
#include <stdarg.h>
using namespace std;
int max1 (int num,int s ...)
{
va_list ap;
int m = s;
Va_start (AP, s);
for (int i = 1; i < num i++)
{
int t = VA_ARG (AP, int);
if (T > m)
m = t;
}
return m;
}
int main (int argc, const char * argv[]) {
//Insert code here ...
Std::cout << "Hello, world!\n";
cout << "Please enter 5 number:";
int a,b,c,d,e;
Cin >> a >> b >> c >> d >> E;
cout << a << b << c << d << e << Endl;
cout << "A and B are the larger:" << max1 (2,a,b) << Endl;
cout << "The larger of 5 numbers are:" << max1 (5,a,b,c,d,e) << Endl;
return 0;
}
The results are:
The MAX1 function is a variable parameter function, and the ellipsis in its parameter table indicates that it may be followed by some parameters, and when writing a variable parameter function, it is usually aided by the va_list and three macros Va_start () in the file system Stdarg.h, Va_arg (), and Va_end ( )。 These parameters are analyzed separately below.
1, va_list: is actually void pointer type, its description is: typedef void * VA_LIST;
2, Va_start (): is actually a macro, void Va_start (va_list argptr,last _param); The first argument is a pointer to the va_list type, and the second parameter is the name of the last fixed parameter in the variable parameter argument list. The function of the macro is to tell the end of the last fixed parameter in the parameter list of the variable argument that the Argptr pointer points to, that is, the argptr pointer to the first variable parameter in the parameter list of the variable argument function, to be prepared for reading the first variable parameter.
3, Va_arg (): macro definition, type Va_arg (va_list argptr, type): The second parameter is the data type of the deformable parameter, if it is a C + + class, it can also be a parent class type. The macro's role is to read a type of data from the memory address that the Argptr pointer points to, while the argptr pointer points to the next variable parameter.
4, Va_end (): Macros, void Va_end (Va_list argptr): The macro has only one va_list parameter, the function is to end the access of variable parameters, so that the variable parameters can return to normal.