(C) Variable Parameter List
C functions use the following Macros in the program:
Void va_start (va_list arg_ptr, prev_param );
Type va_arg (va_list arg_ptr, type );
Void va_end (va_list arg_ptr );
Va_list: A type used to save the information required by macros va_start, va_arg, and va_end. To access parameters in the variable-length parameter list, you must declare
Definition of an object of the va_list type: typedef char * va_list;
Va_start: the macro used to access the parameter in the variable length parameter list. It initializes the object declared with va_list, and the initialization result is used by the macro va_arg and
Use va_end;
Va_arg: expands into a macro of an expression that has the value and type of the next parameter in the variable-length parameter list. Each call to va_arg will be modified
Object declared with va_list so that the object points to the next parameter in the parameter list;
Va_end: This macro enables the program to normally return data from the function referenced by the macro va_start in the variable length parameter list.
Va here is the meaning of variable-argument (variable Parameter.
These macros are defined in stdarg. h, so the program that uses variable parameters should contain this header file. next we will write a simple variable parameter function. The function should have at least one integer parameter, and the second parameter is also an integer, which is optional. the function only prints the values of these two parameters.
Problem description:
Use the variable parameter list to calculate the maximum value among n integer numbers and output the result.
The Code is as follows:
/******** Variable Parameter List **********/# include
# Include
/* ANSI standard declaration method. The ellipsis in parentheses indicates the optional parameter */int Max (int n ,...) /* calculate the maximum n count */{va_list arg;/* define the structure of the stored function parameter */int max = 0; int I; va_start (arg, n ); /* argp points to the first optional parameter passed in. msg is the final parameter */for (I = 0; I
Max) {max = tmp;} va_end (arg);/* Get the variable parameters to end */return max;} int main () {int ret = Max (, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); printf ("% d \ n", ret); return 0 ;}