In C language, scanf is the most commonVariable parametersFunction to defineVariable parametersThe function is very simple, such as void print (int n ,...), the parameter processing in the function is mainly through stack operations, and the real parameters of the C function are pushed from right to left into the stack. major Stack operations (both macro operations) include va_list and va_start.
, Va_arg, va_end, which is defined as follows:
Typedef char * va_list;
# DEFINE _ intsizeof (N) (sizeof (n) + sizeof (INT)-1 )&~ (Sizeof (INT)-1 ))
# Define va_start _ crt_va_start
# Define va_arg _ crt_va_arg
# Define va_end _ crt_va_end
# DEFINE _ crt_va_start (AP, V) (AP = (va_list) _ addressof (v) + _ intsizeof (v ))
# DEFINE _ crt_va_arg (AP, t) (* (T *) (AP + = _ intsizeof (t)-_ intsizeof (t )))
# DEFINE _ crt_va_end (AP) (AP = (va_list) 0)
Va_start (AP, V): obtains the first address of the variable parameter list, and then assigns it to the AP, which is similar to AP = & V + sizeof (V) (memory alignment and type conversion are not considered here)
Va_arg (AP, T): gets the variable parameter value of the returned type T and points the AP to the next parameter: AP + = sizeof (t ), T is the data type of variable parameters, such as int and float.
Va_end (AP): Initialize the AP
Va_start (AP, v) va_arg (AP, T) va_end (AP) can be used together to ensure program robustness.
One useVariable parametersSimple Program:
# Include <stdio. h>
# Include <stdarg. h> // includes va_list and other definitions
Float sum (float first,...) //,... representsVariable parametersFunction
{
Float I = first, sum = 0;
Va_list maker; // all parameters of the va_list function can be saved as a list.
Va_start (maker, first); // you can specify the start position of the list.
While (I! =-1.0)
{
Sum + = I;
I = va_arg (maker, float); // returns the current value of the maker list and points to the next position in the list.
}
Return sum;
}
Void main (void)
{
Printf ("sum is: % F \ n", sum (2.0, 8.0, 8.5,-1.0); // function call
}
Address: http://blog.163.com/zwh50687695/blog/static/223116332010026112224105/