Three functions Va_start, Va_end,va_arg and one type va_list are provided in the C language stdarg.h header file. Using them, we can easily implement a variable parameter function. Let's start with a brief look at these three functions.
Suppose you now have a function called F, whose function is defined as:
void f (int a, int b, ...)
So, inside the function, to get these mutable parameters, you need to take advantage of the three functions of Va_start, Va_arg, and Va_end.
Variables of type va_list can be used to store variable types of variables, which can traverse variable variables;
Va_list AP
Before using the AP, the va_start must be called to associate the AP with the mutable parameter;
Va_start (AP, B);
The second parameter of Va_start is the parameter of the last non-mutable parameter in the function parameter list;
You can then call Va_arg to access the parameters;
Type Va_arg (AP, type);
Once the variable is processed, the va_end should be called once before the program finishes.
void Va_end (AP);
The following program shows a technique used in conjunction with a variadic function and the CSTRING::FORMATV function. This technology is widely used in VC + + programming:
#include <iostream>#include<cstring>#include<string.h>#include<atltime.h>usingnamespace::std;voidwritelogentry (LPCTSTR pstrformat, ...) {CTime timewrite; Timewrite=Ctime::getcurrenttime (); CString Str= Timewrite.format (_t ("%d%b%y%h:%m:%s-")); AtlTrace (str); Va_list args; Va_start (args, Pstrformat); Str. FORMATV (Pstrformat, args); AtlTrace (str); return;}intMain () {Writelogentry (_t ("Start program!\n")); Writelogentry (_t ("Program has execute%d lines!\n"),201); Writelogentry (_t ("error%d occured at%d line!\n"),1170, -); Writelogentry (_t ("Program abouted!"));}
The realization of variable parameter function in C + +