Variable Length Function

Source: Internet
Author: User

A variable-length function is a function with variable numbers and variable parameter types.

It is possible to design a function with variable number of parameters and variable parameter types. The most common examples are printf, scanf, and format functions in advanced languages. In C/C ++, to notify the compiler of variable parameter numbers and types (that is, indefinite and unknown), the Declaration of the function must end at three points.

View plaincopy
Clipboardprint?
  1. // Printf function declaration
  2. Int printf (const char * _ format ,...);
  3. // Scanf function declaration
  4. Int scanf (const char * _ format ,...);
  5. // Customize the Variable Length Parameter Function func Declaration
  6. Int func (int A, int B ,...);

// Printf function declaration </P> <p> int printf (const char * _ format ,...); </P> <p> // scanf function declaration </P> <p> int scanf (const char * _ format ,...); </P> <p> // Declaration of the Variable Length function func </P> <p> int func (int A, int B ,...); <br/>

The above Declaration of the func function indicates that the function has at least two Integer Parameters and zero or multiple unknown parameters following it. In C/C ++, any function declared using the variable length parameter must have at least one specified parameter (also known as a mandatory parameter), that is, the type of at least one parameter is known, however, all parameter settings cannot be omitted by using three points, and known specified parameters must be declared at the leftmost end of the function.

View plaincopy
Clipboardprint?
  1. // The following statement is invalid.
  2. Int func (...); // Error
  3. Int func (..., int A); // Error

// The following statement is invalid </P> <p> int func (...); // error </P> <p> int func (..., int A); // Error
Implementation of variable length parameter functions

How is a function with variable length parameters implemented? The key to implementing a variable-length parameter function is how to use the parameter. If you specify a parameter, you can directly access it with the specified parameter name, but not the specified parameter? We know that parameter transfer is implemented through stacks during function calls. Generally, all calls are from right to left. Therefore, parameters and parameters are adjacent to each other, knowing the type and address of the previous parameter, you can obtain the content of the latter parameter based on the type of the latter parameter. For variable-length parameter functions, combined with certain conditions, we can obtain the omitted parameter content based on the last specified parameter. For example, for the function func, if we know the address and type of parameter B, we can know the stack address of the first variable parameter (if any ), if you know the type of the first variable parameter, you can know the content of the first variable parameter and the address of the second variable parameter (if any ). Similarly, you can access all parameters of a Variable Parameter Function.

So how should we specify the "conditions" for appeal? The simplest way is to format placeholders like functions such as printf. Analyze and format the string parameters. You can see the type and number of variable parameters through predefined format placeholders to obtain the content of each parameter. Generally, for functions with the same variable parameter type, you can directly specify the number and type of variable parameters in the mandatory parameter. In this way, you can also obtain the content of each parameter.

Either method involves the stack address offset operation. Combined with the stack storage mode and the system data type length, we can easily get the stack address offset based on the variable parameter type. The following describes how to use three standard macros, va_start, va_arg, and va_end, to offset stack addresses and obtain variable parameter content. These three macros are defined in the stdarg. h header file. They can automatically obtain the offset of each data type on the corresponding platform based on the predefined system platform.

View plaincopy
Clipboardprint?
  1. // Process for accessing variable parameters
  2. Va_list ARGs; // defines a variable parameter list.
  3. Va_start (ARGs, ARG); // initialize ARGs to point to the next parameter of the mandatory parameter ARG;
  4. Va_arg (ARGs, type); // obtain the content of the current parameter and direct the ARGs to the next Parameter
  5. ... // Obtain all variable parameters cyclically
  6. Va_end (ARGs); // release ARGs

// Access the variable parameter Process </P> <p> va_list ARGs; // define a variable parameter list </P> <p> va_start (ARGs, ARG ); // initialize ARGs to point to the next parameter of the mandatory parameter ARG; </P> <p> va_arg (ARGs, type ); // obtain the content of the current parameter and direct the ARGs to the next parameter </P> <p>... // obtain all variable parameters cyclically </P> <p> va_end (ARGs); // release ARGs <br/>

Implement a simple variable length parameter function:

View plaincopy
Clipboardprint?
  1. // Sum is the sum function, and its parameter type is int, but the number of parameters is not fixed
  2. // The first parameter (mandatory parameter) n specifies the number of variable parameters
  3. Int sum (unsigned int N ,...)
  4. {
  5. Int sum = 0;
  6. Va_list ARGs;
  7. Va_start (ARGs, N );
  8. While (n> 0)
  9. {
  10. // Obtain the parameter values in sequence through va_arg (ARGs, INT)
  11. Sum + = va_arg (ARGs, INT );
  12. N --;
  13. }
  14. Va_end (ARGs );
  15. Return sum;
  16. }

// Sum is the sum function, and its parameter type is int, but the number of parameters is not fixed <br/> // The first parameter (mandatory parameter) N specifies the number of variable parameters that follow <br/> int sum (unsigned int N ,...) <br/>{< br/> int sum = 0; <br/> va_list ARGs; <br/> va_start (ARGs, N ); <br/> while (n> 0) <br/> {<br/> // pass va_arg (ARGs, INT) obtain the parameter values in sequence <br/> sum + = va_arg (ARGs, INT); <br/> n --; <br/>}< br/> va_end (ARGs ); <br/> return sum; <br/>}

Pay attention to the call of variable parameter functions. The actual number of variable parameters must be greater than or equal to the number specified in the preceding mandatory parameter, that is, it does not matter if there are more parameters, but it cannot be less. If it is missing, it will access the stack area other than the function parameters, which may cause the program to collapse. If the type specified in the preceding mandatory parameter does not match the actual parameter type, the program may crash.

 

Variable-length parameter functions and default parameter functions

 

When a function with variable-length parameters is declared and defined, the number and type of parameters are variable. When a function is called, the parameter status is certain. When the default parameter function is declared and defined, the parameter type and quantity are fixed, but the default value is specified for some parameters. You can call this default Parameter Function by omitting (not specifying) some parameters. However, the default parameter function still uses all the parameters specified in the declaration, except that the compiler has done a good job and automatically assigned the default values to the later parameters; the variable-length parameter function only uses the parameters provided during the call.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.