Document directory
- I. Basics
- Ii. Knowledge Extension
I. Basic part 1.1 what is a variable length parameter
Variable Length Parameter: As the name implies, the parameter length (quantity) of the function is variable. For example, the C-language printf series (formatted input and output) functions are variable parameters. The Declaration of the printf function is as follows:
Int printf (const char * format ,...);
Variable Parameter Function declaration is similar.
1.2 How to Implement
Variable parameters in C language are implemented through three macros (va_start, va_end, va_arg) and one type (va_list,
Void va_start (va_list AP, paramn );
Parameters:
AP: Address of the Variable Parameter List
Paramn: the specified parameter.
Function: Initialize the variable parameter list (put the parameter address of the function after paramn into the AP ).
Void va_end (va_list AP );
Function: Disable the initialization list (leave the AP empty ).
Type va_arg (va_list AP, type );
Function: return the value of the next parameter.
Va_list: stores the parameter type information.
Well, considering the three macros and one type above, we can guess how to implement the Variable Length Parameter Function in C language:Use va_start to obtain the parameter list (address) and store it in the AP. Use va_arg to obtain values one by one. Finally, use va_arg to empty the AP.
Example:
# Include <stdio. h> # include <stdarg. h> # define end-1int va_sum (INT first_num ,...) {// (1) define the parameter list va_list AP; // (2) initialize the parameter list va_start (AP, first_num); int result = first_num; int temp = 0; // get the parameter value while (temp = va_arg (AP, INT ))! = END) {result + = temp;} // close the parameter list va_end (AP); return result;} int main () {int sum_val = va_sum (1, 2, 3, 4, 5, end); printf ("% d", sum_val); Return 0 ;}Ii. Knowledge ExtensionAs you may have guessed, what do I need to expand ?! Pai_^
Two function call conventions_ Stdcall (C ++ default)
- The parameter is pushed to the stack from right to left.
- The function is called to modify the stack.
- The function name (at the compiler level) is automatically followed by a leading underline followed by a @ symbol followed by the parameter size.
_ Cdecl (C language default)
- The parameter is pushed to the stack from right to left.
- The caller is clear about the parameters. manually clear the stack. The called function does not require the caller to pass many parameters. Too many or too few parameters are passed by the caller, and even different parameters do not generate errors in the compilation phase.
Then, the call method of the Variable Parameter Function is (or can only be) :__ cdecl.
I was planning to write a little more extensions, and I was worried that the text would not be correct. So if you are interested, you can go to the articles in the reference materials and have some detailed introductions.