1 , variable-parameter functions
<stdarg.h> A number of macros are defined in the header file for functions with variable parameters, as follows
VA _list : This type declares a local state variable, assuming that the variable is named va < Span lang= "ZH-CN" (for the following description), used to traverse the function.
VA _start : This macro initializes the state variable va to call before calling va_arg Span style= "Font-family:wenquanyi Micro Hei" > va_end
Va_arg: This macro returns the value of the next parameter in the parameter table, with the internal pointer (invaTo the next parameter, the type of the next parameter istypespecified to makeVa_argis able to calculate its length in the stack, callingVa_startafter the first callVa_argreturns the value of the first mutable parameter.
Va_end : This function or macro is used Va_arg called after all parameters have been read, va perform the necessary finishing operations.
va_copy:C99added, this macro isdestcopy insrc's current state, a second pointer is generated in the parameter table, which can then be independentlysrcwith thedestAdoptVa_arg,destin order to be likesrccalled in the sameVa_end.
The following is a simple example:
#include <stdio.h> #include <stdarg.h>void printargs (int num, ...) { va_list va; Va_start (VA, num); int index = 0; int value = num; while (1) { printf ("args[%d] =%d\n", index, value); if (value = Va_arg (VA, int)) = = 0) {break ; } index++; } Va_end (VA);} int main (void) { Printargs (1, 2, 3, 4, 5, 0); return 0;}
The output results are as follows:
Args[0] = 1 args[1] = 2 args[2] = 3 args[3] = 4 args[4] = 5
2 , variable-parameter macros
Variable-parameter macros are available in two forms, such as the following example:
#define MULTIARGS (format, ...) printf (format, __va_args__) #define PRINTARGS (format, ARGS ...) printf (format, # #args) Multiargs ("%s,%s\n", "Hello", "world!"); Hello, world!. Printargs ("%s,%s\n", "Hello", "C language!"); Hello, c language!
It is important to note that the difference in the form of the parameter list of the two parameter macros above Printargs of the Macro Arg you cannot have a comma after a parameter.
Functions and macros for variable parameters