The principle and use of c variable parameter (variable argument)

Source: Internet
Author: User
Tags variadic

This article mainly introduces the function of variable parameter, then analyzes its principle, how the programmer realizes and encapsulates them, and finally it is possible problems and avoid measures.

VA functions (variable argument function), the number of arguments variable function, also known as variable parameter function. The VA functions provided by the system to programmers are very few in C + + programming. The *printf ()/*scanf () series function, which is used to format a string at input and output, and a exec* () series function to execute an external file in the program (the main (int argc,char*argv[) is not counted, so that main () is also a variadic function , it is a function of exec* () with special functions and meanings after encapsulation, at least at the principle level.
Many similarities). Because of the uncertainty of the number of parameters, the VA function has great flexibility, ease of use, it is tempting for programmers who have not used variadic functions, so how to write their VA functions, the timing of the use of VA functions, the implementation of the compiler and how. The author gives some humble opinions about the VA function.

 
A variadic function is introduced starting with a formatted string function that everyone is familiar with.
Prototype: int printf (const char * format, ...);
The parameter format represents how to format a string of instructions, ...
Represents an optional parameter that is passed to the "..." parameter when invoked, depending on the actual situation.
The system provides functions for VPRINTF series formatted strings, which are used by programmers to encapsulate their own I/O functions.

 

<pre lang= "C" escaped= "true" >
int vprintf/vscanf (const char * format, va_list AP); Format strings from standard input/output
int vfprintf/vfsacanf (FILE * stream, const char * format, va_list AP);
From a file stream
int vsprintf/vsscanf (char * s, const char * format, va_list AP); From a string

Example 1: Format to a file stream that can be used for log files
FILE *logfile;
int writelog (const char * format, ...)
{
Va_list arg_ptr;
Va_start (arg_ptr, format);
int nwrittenbytes = vfprintf (logfile, format, arg_ptr);
Va_end (ARG_PTR);
return nwrittenbytes;
}
...
When called, there is no difference from using printf ().
Writelog ("%04d-%02d-%02d%02d:%02d:%02d%s/%04d logged out.",
Nyear, Nmonth, Nday, Nhour, Nminute, szUserName, Nuserid);
</pre>

Similarly, you can format input from a file, or format the string for standard input and output. In Example 1 above, the Writelog () function can accept input with a variable number of arguments, in essence, its implementation requires vprintf () support. How to really implement your own variadic functions, including controlling each incoming optional parameter.

C Language Support VA function, as the C language extension--c++ also support VA functions, but in C + + is not recommended, C + + introduced polymorphism can also be used to implement a variable number of functions. However, the overloaded functionality of C + + can only be a limited number of parameters to anticipate. In contrast, the VA function in C can define an infinite number of overloaded functions equivalent to C + +, which is powerless. The advantages of the VA function are in terms of convenience and ease of use, which can make the code more concise. C compiler in order to unify the implementation on different hardware architectures, hardware platforms, and to increase the portability of code, provides a series of macros to shield the different hardware environment differences.
In the ANSI C standard, the VA macros are defined in Stdarg.h, which are: Va_list,va_start (), Va_arg (), Va_end ().

<pre lang= "C" escaped= "true" >
Example 2: The sum of squares of any natural number:
int sqsum (int n1, ...)
{
Va_list arg_ptr;
int nsqsum = 0, n = N1;
Va_start (Arg_ptr, N1);
while (n > 0)
{
Nsqsum + = (n * n);
n = va_arg (arg_ptr, int);
}
Va_end (ARG_PTR);
return nsqsum;
}
When called
int nsqsum = Sqsum (7, 2, 7, 11,-1);
The prototype declaration format for variadic functions is:
Type vafunction (type arg1, type arg2, ...);
</pre>

The parameters can be divided into two parts: fixed parameter with number determination and optional parameter with variable number. The function requires at least one fixed parameter, the declaration of a fixed argument is the same as a normal function, and an optional parameter is declared with a "..." when the number is indeterminate. A fixed parameter and an optional parameter make up a parameter list of a function.

With this simple example 2 above, let's look at the role of each va_xxx:
Va_list arg_ptr: Defines a pointer to a variable number of parameter lists;
Va_start (Arg_ptr, ArgN): Causes the parameter list pointer arg_ptr to point to the first optional parameter in the function argument list, stating: ArgN is a fixed parameter before the first optional parameter, (or, last fixed argument; ...). Previous parameter), the order of the parameters in the function argument list in memory is consistent with the order in which the function is declared. If there is a declaration of a VA function that is void va_test (char A, char B, char C, ...), then its fixed parameter is a,b,c, the last fixed argument argn C, and therefore is
Va_start (Arg_ptr, C).

Va_arg (Arg_ptr, type): Returns the parameter in the argument list that is referred to by the pointer arg_ptr, the return type is kind, and the pointer arg_ptr points to the next parameter in the parameter list.
Va_copy (dest, SRC): The DEST,SRC type is va_list,va_copy () used to copy the parameter list pointer, and dest is initialized to SRC.
Va_end (ARG_PTR): Clears the argument list and invalidates the parameter pointer arg_ptr.

Description: After the pointer arg_ptr is invalidated, the arg_ptr can be restored by calling Va_start (), Va_copy (). Every call to Va_st
Art ()/va_copy () must be matched with the corresponding va_end (). The parameter pointer can be moved back and forth in the parameter list, but must be within va_start (). Va_end ().

The principle and use of c variable parameter (variable argument)

Related Article

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.