Variable length parameter function (reprint) __ function

Source: Internet
Author: User

The function of variable length parameter is a function with variable number of parameters and indefinite parameter type.

It is possible to design a function with variable number of parameters and indefinite parameter types, the most common example being the printf function, the scanf function, and the format function of the advanced language. In C + +, to tell a compiler function that the number and type of parameters are variable (that is, indeterminate, unknown), you must end the declaration of the function at three points.

View plain Copy to clipboard print?      The declaration of printf function int printf (const char * _format, ...);      scanf function declares int scanf (const char * _format, ...);   Custom variable-length parameter function func declaration int func (int a,int b,...); The declaration of printf function int printf (const char * _format, ...); scanf function declares int scanf (const char * _format, ...); Custom variable-length parameter function func declaration int func (int a,int b,...);

The declaration of the Func function above indicates that the function has at least two integer parameters and 0 or more unknown types of parameters immediately following it. In C + +, any function declared with a variable-length parameter must have at least one specified argument (also known as the Coercion parameter), that is, the type of at least one argument is known, and the specified parameter cannot be omitted with three points, and the specified argument must be declared at the leftmost end of the function. View plain Copy to clipboard print? The following declarations are illegal int func (...). /Error int func (..., int a);//error//The following declaration is illegal int func (...); /Error int func (..., int a);//Error
Realization of variable length parameter function

How does a function with variable-length arguments be implemented? The realization of variable length parameter function is the key to how to use parameters, specify the parameters to say, directly using the specified parameter name access, but unspecified parameters. We know that the parameter passes are implemented through the stack in the function call process, the general call is from the right to the left of the sequential pressure parameters into the stack, so the parameters and parameters are adjacent to know the type and address of the previous parameter, according to the type of the latter parameter can get the content of the latter parameter. For variable-length parametric functions, we can obtain the omitted parameters after the last specified parameter, combining certain conditions. For example, for function func, we know the address and type of parameter B, we know the stack address of the first variable parameter (if any), and if you know the type of the first variable parameter, you know the contents of the first variable parameter and the address of the second variable parameter, if any. By analogy, you can implement access to all parameters of a variable parameter function.

So, how to specify the "certain conditions" of the appeal. The easiest way to do this is to use a formatted placeholder like a function such as printf. Parse the formatted string parameter to get the contents of each parameter by using the predefined format placeholder to know the type and number of variable parameters. A function that is generally the same for a variable parameter type can also specify the number and type of variable parameters directly in the coercion parameter, so that the contents of each parameter can be obtained.

Either way, it involves an operation on the stack address offset. With the word length of the stack storage mode and system data type, we can easily get the offset of the stack address according to the type of the variable parameter. Here is a brief introduction to using Va_start, Va_arg, va_end three standard macros to implement stack address offset and get variable parameter content. These three macros are defined in the Stdarg.h header file, and they can automatically get offsets on the respective data types on the platform based on the predefined system platform. View plain Copy to clipboard print? Access variable parameter flow va_list args;       Define a variable argument list va_start (ARGS,ARG);//Initialize the args to the next argument to force parameter arg; Va_arg (Args,type), get the current parameter content and refer args to the next argument ...//loop fetch all variable parameter content va_end (args);//release args//access variable parameter process va_list args; Define a variable argument list va_start (ARGS,ARG);//Initialize the args to the next argument to force parameter arg; Va_arg (Args,type); Get the current parameter contents and refer args to the next parameter ...//loop to get all variable parameter content va_end (args);/release Args

Implement a simple variable-length parameter function: View plain copy to clipboard print?//sum is a sum function with a parameter type of int, with an indefinite number of arguments   // The first argument (force parameter) n specifies how many variable parameters are followed    int sum (Unsigned int n,...)    {      int sum=0;      va_list args;       va_start (args,n);      while (n>0)        {       //Gets the value of the parameter by Va_arg (args,int)          sum+=va_arg (args,int);        n--;       }      va_end (args);      return sum;  }   //sum is a sum function with a parameter type of int, but an indefinite number of arguments//The first argument (force parameter) n specifies how many variable parameters int sum (unsigned int n,...) is followed {int sum=0; va_list args va_start (args,n); while (n>0) {//through Va_arg (Args,int) sequentially gets the value of the parameter Sum+=va_arg (args,int); n--;} VA _end (args); return sum; }


For a call to a variable parameter function, it is important to note that the actual number of variable parameters must be more than the number specified in the preceding force parameter, or not less than, or the subsequent parameters will not matter a bit more, but not less, if less then access to the stack area outside the function parameters, which may cause the program to be blown off. The type that is specified in the preceding coercion parameter and the type of the subsequent actual argument may also cause the program to crash.

variable length parameter function and default parameter function

A function that has variable-length parameters is variable in number and type of arguments when declaring a definition, and the state of the parameter is certain when the call is run. The default parameter function has a certain parameter type and number when declaring the definition, except that the default parameter function is called by omitting (unspecified) partial arguments. However, the default parameter function uses all the parameters specified in the declaration, except that the compiler makes a Shinshu that automatically assigns a default value to the latter part of the parameter, and the variable-length parameter function uses only the arguments that are provided when the call is run.

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.