A function with variable parameters is often encountered at work
The variable parameters currently provided by C are stated as
void function (const char *format, ...);
This allows variable parameters to be used in the function
C provides several macros for using variable parameters
Va_list
Va_start
Va_arg
Va_end
which
Va_list used to define a variable to get a variable parameter pointer
Va_start is used to initialize a pointer defined by va_list
Va_arg to get the true type data for the corresponding pointer
Va_end for emptying the va_list defined pointer
The following is a concrete example of a variable parameter, which can be used to calculate the and of any number of int values
int sum (int number, ...)
{
va_list arg_ptr = NULL;
Va_start (arg_ptr, number);
int sum = 0;
for (int i=0; i<number; i++)
{
Sum + = va_arg (arg_ptr, int);
}
va_end (ARG_PTR);
return sum;
}
2 principle:
Let's see what these macros have done.
typedef char * VA_LIST; This is just a redefinition ...
Get the address of V
#define _ADDRESSOF (V) (& (v))
The size of the integer byte of n, which must be an integer multiple of sizeof (int). If sizeof (n) is 5, _intsizeof (n) is 8 (assuming 32-bit machine)
#define _INTSIZEOF (N) ((sizeof (n) + sizeof (int)-1) & ~ (sizeof (int)-1))
The address of V plus the size of V
#define VA_START (AP,V) (AP = (va_list) _addressof (v) + _intsizeof (v))
To increase the size of the AP and obtain the data of the address of the original AP, forcing the conversion to type T
This corresponds to (* (T *) AP)
(AP + = _intsizeof (t))
This one macro is equivalent to doing two things
#define VA_ARG (Ap,t) (* (t *) (AP + = _intsizeof (t))-_intsizeof (t)))
Give the AP 0
#define VA_END (AP) (AP = (va_list) 0)
Variable Parameter Learning Summary